xref: /qemu/migration/migration.c (revision 0534248a6b515cb4dea29a6fd6c256dc77f2a953)
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 "qobject/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     once = false;
1899 }
1900 
1901 void qmp_migrate_recover(const char *uri, Error **errp)
1902 {
1903     MigrationIncomingState *mis = migration_incoming_get_current();
1904 
1905     /*
1906      * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1907      * callers (no one should ignore a recover failure); if there is, it's a
1908      * programming error.
1909      */
1910     assert(errp);
1911 
1912     if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1913         error_setg(errp, "Migrate recover can only be run "
1914                    "when postcopy is paused.");
1915         return;
1916     }
1917 
1918     /* If there's an existing transport, release it */
1919     migration_incoming_transport_cleanup(mis);
1920 
1921     /*
1922      * Note that this call will never start a real migration; it will
1923      * only re-setup the migration stream and poke existing migration
1924      * to continue using that newly established channel.
1925      */
1926     qemu_start_incoming_migration(uri, false, NULL, errp);
1927 }
1928 
1929 void qmp_migrate_pause(Error **errp)
1930 {
1931     MigrationState *ms = migrate_get_current();
1932     MigrationIncomingState *mis = migration_incoming_get_current();
1933     int ret = 0;
1934 
1935     if (migration_postcopy_is_alive(ms->state)) {
1936         /* Source side, during postcopy */
1937         Error *error = NULL;
1938 
1939         /* Tell the core migration that we're pausing */
1940         error_setg(&error, "Postcopy migration is paused by the user");
1941         migrate_set_error(ms, error);
1942         error_free(error);
1943 
1944         qemu_mutex_lock(&ms->qemu_file_lock);
1945         if (ms->to_dst_file) {
1946             ret = qemu_file_shutdown(ms->to_dst_file);
1947         }
1948         qemu_mutex_unlock(&ms->qemu_file_lock);
1949         if (ret) {
1950             error_setg(errp, "Failed to pause source migration");
1951         }
1952 
1953         /*
1954          * Kick the migration thread out of any waiting windows (on behalf
1955          * of the rp thread).
1956          */
1957         migration_rp_kick(ms);
1958 
1959         return;
1960     }
1961 
1962     if (migration_postcopy_is_alive(mis->state)) {
1963         ret = qemu_file_shutdown(mis->from_src_file);
1964         if (ret) {
1965             error_setg(errp, "Failed to pause destination migration");
1966         }
1967         return;
1968     }
1969 
1970     error_setg(errp, "migrate-pause is currently only supported "
1971                "during postcopy-active or postcopy-recover state");
1972 }
1973 
1974 bool migration_is_blocked(Error **errp)
1975 {
1976     GSList *blockers = migration_blockers[migrate_mode()];
1977 
1978     if (qemu_savevm_state_blocked(errp)) {
1979         return true;
1980     }
1981 
1982     if (blockers) {
1983         error_propagate(errp, error_copy(blockers->data));
1984         return true;
1985     }
1986 
1987     return false;
1988 }
1989 
1990 /* Returns true if continue to migrate, or false if error detected */
1991 static bool migrate_prepare(MigrationState *s, bool resume, Error **errp)
1992 {
1993     if (resume) {
1994         if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1995             error_setg(errp, "Cannot resume if there is no "
1996                        "paused migration");
1997             return false;
1998         }
1999 
2000         /*
2001          * Postcopy recovery won't work well with release-ram
2002          * capability since release-ram will drop the page buffer as
2003          * long as the page is put into the send buffer.  So if there
2004          * is a network failure happened, any page buffers that have
2005          * not yet reached the destination VM but have already been
2006          * sent from the source VM will be lost forever.  Let's refuse
2007          * the client from resuming such a postcopy migration.
2008          * Luckily release-ram was designed to only be used when src
2009          * and destination VMs are on the same host, so it should be
2010          * fine.
2011          */
2012         if (migrate_release_ram()) {
2013             error_setg(errp, "Postcopy recovery cannot work "
2014                        "when release-ram capability is set");
2015             return false;
2016         }
2017 
2018         migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
2019                           MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP);
2020 
2021         /* This is a resume, skip init status */
2022         return true;
2023     }
2024 
2025     if (migration_is_running()) {
2026         error_setg(errp, "There's a migration process in progress");
2027         return false;
2028     }
2029 
2030     if (runstate_check(RUN_STATE_INMIGRATE)) {
2031         error_setg(errp, "Guest is waiting for an incoming migration");
2032         return false;
2033     }
2034 
2035     if (runstate_check(RUN_STATE_POSTMIGRATE)) {
2036         error_setg(errp, "Can't migrate the vm that was paused due to "
2037                    "previous migration");
2038         return false;
2039     }
2040 
2041     if (kvm_hwpoisoned_mem()) {
2042         error_setg(errp, "Can't migrate this vm with hardware poisoned memory, "
2043                    "please reboot the vm and try again");
2044         return false;
2045     }
2046 
2047     if (migration_is_blocked(errp)) {
2048         return false;
2049     }
2050 
2051     if (migrate_mapped_ram()) {
2052         if (migrate_tls()) {
2053             error_setg(errp, "Cannot use TLS with mapped-ram");
2054             return false;
2055         }
2056 
2057         if (migrate_multifd_compression()) {
2058             error_setg(errp, "Cannot use compression with mapped-ram");
2059             return false;
2060         }
2061     }
2062 
2063     if (migrate_mode_is_cpr(s)) {
2064         const char *conflict = NULL;
2065 
2066         if (migrate_postcopy()) {
2067             conflict = "postcopy";
2068         } else if (migrate_background_snapshot()) {
2069             conflict = "background snapshot";
2070         } else if (migrate_colo()) {
2071             conflict = "COLO";
2072         }
2073 
2074         if (conflict) {
2075             error_setg(errp, "Cannot use %s with CPR", conflict);
2076             return false;
2077         }
2078     }
2079 
2080     if (migrate_init(s, errp)) {
2081         return false;
2082     }
2083 
2084     return true;
2085 }
2086 
2087 static void qmp_migrate_finish(MigrationAddress *addr, bool resume_requested,
2088                                Error **errp);
2089 
2090 static void migrate_hup_add(MigrationState *s, QIOChannel *ioc, GSourceFunc cb,
2091                             void *opaque)
2092 {
2093         s->hup_source = qio_channel_create_watch(ioc, G_IO_HUP);
2094         g_source_set_callback(s->hup_source, cb, opaque, NULL);
2095         g_source_attach(s->hup_source, NULL);
2096 }
2097 
2098 static void migrate_hup_delete(MigrationState *s)
2099 {
2100     if (s->hup_source) {
2101         g_source_destroy(s->hup_source);
2102         g_source_unref(s->hup_source);
2103         s->hup_source = NULL;
2104     }
2105 }
2106 
2107 static gboolean qmp_migrate_finish_cb(QIOChannel *channel,
2108                                       GIOCondition cond,
2109                                       void *opaque)
2110 {
2111     MigrationAddress *addr = opaque;
2112 
2113     qmp_migrate_finish(addr, false, NULL);
2114 
2115     cpr_state_close();
2116     migrate_hup_delete(migrate_get_current());
2117     qapi_free_MigrationAddress(addr);
2118     return G_SOURCE_REMOVE;
2119 }
2120 
2121 void qmp_migrate(const char *uri, bool has_channels,
2122                  MigrationChannelList *channels, bool has_detach, bool detach,
2123                  bool has_resume, bool resume, Error **errp)
2124 {
2125     bool resume_requested;
2126     Error *local_err = NULL;
2127     MigrationState *s = migrate_get_current();
2128     g_autoptr(MigrationChannel) channel = NULL;
2129     MigrationAddress *addr = NULL;
2130     MigrationChannel *channelv[MIGRATION_CHANNEL_TYPE__MAX] = { NULL };
2131     MigrationChannel *cpr_channel = NULL;
2132 
2133     /*
2134      * Having preliminary checks for uri and channel
2135      */
2136     if (!uri == !channels) {
2137         error_setg(errp, "need either 'uri' or 'channels' argument");
2138         return;
2139     }
2140 
2141     if (channels) {
2142         for ( ; channels; channels = channels->next) {
2143             MigrationChannelType type = channels->value->channel_type;
2144 
2145             if (channelv[type]) {
2146                 error_setg(errp, "Channel list has more than one %s entry",
2147                            MigrationChannelType_str(type));
2148                 return;
2149             }
2150             channelv[type] = channels->value;
2151         }
2152         cpr_channel = channelv[MIGRATION_CHANNEL_TYPE_CPR];
2153         addr = channelv[MIGRATION_CHANNEL_TYPE_MAIN]->addr;
2154         if (!addr) {
2155             error_setg(errp, "Channel list has no main entry");
2156             return;
2157         }
2158     }
2159 
2160     if (uri) {
2161         /* caller uses the old URI syntax */
2162         if (!migrate_uri_parse(uri, &channel, errp)) {
2163             return;
2164         }
2165         addr = channel->addr;
2166     }
2167 
2168     /* transport mechanism not suitable for migration? */
2169     if (!migration_channels_and_transport_compatible(addr, errp)) {
2170         return;
2171     }
2172 
2173     if (s->parameters.mode == MIG_MODE_CPR_TRANSFER && !cpr_channel) {
2174         error_setg(errp, "missing 'cpr' migration channel");
2175         return;
2176     }
2177 
2178     resume_requested = has_resume && resume;
2179     if (!migrate_prepare(s, resume_requested, errp)) {
2180         /* Error detected, put into errp */
2181         return;
2182     }
2183 
2184     if (cpr_state_save(cpr_channel, &local_err)) {
2185         goto out;
2186     }
2187 
2188     /*
2189      * For cpr-transfer, the target may not be listening yet on the migration
2190      * channel, because first it must finish cpr_load_state.  The target tells
2191      * us it is listening by closing the cpr-state socket.  Wait for that HUP
2192      * event before connecting in qmp_migrate_finish.
2193      *
2194      * The HUP could occur because the target fails while reading CPR state,
2195      * in which case the target will not listen for the incoming migration
2196      * connection, so qmp_migrate_finish will fail to connect, and then recover.
2197      */
2198     if (s->parameters.mode == MIG_MODE_CPR_TRANSFER) {
2199         migrate_hup_add(s, cpr_state_ioc(), (GSourceFunc)qmp_migrate_finish_cb,
2200                         QAPI_CLONE(MigrationAddress, addr));
2201 
2202     } else {
2203         qmp_migrate_finish(addr, resume_requested, errp);
2204     }
2205 
2206 out:
2207     if (local_err) {
2208         migrate_fd_error(s, local_err);
2209         error_propagate(errp, local_err);
2210     }
2211 }
2212 
2213 static void qmp_migrate_finish(MigrationAddress *addr, bool resume_requested,
2214                                Error **errp)
2215 {
2216     MigrationState *s = migrate_get_current();
2217     Error *local_err = NULL;
2218 
2219     if (!resume_requested) {
2220         if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2221             return;
2222         }
2223     }
2224 
2225     if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
2226         SocketAddress *saddr = &addr->u.socket;
2227         if (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
2228             saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
2229             saddr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
2230             socket_start_outgoing_migration(s, saddr, &local_err);
2231         } else if (saddr->type == SOCKET_ADDRESS_TYPE_FD) {
2232             fd_start_outgoing_migration(s, saddr->u.fd.str, &local_err);
2233         }
2234 #ifdef CONFIG_RDMA
2235     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_RDMA) {
2236         rdma_start_outgoing_migration(s, &addr->u.rdma, &local_err);
2237 #endif
2238     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_EXEC) {
2239         exec_start_outgoing_migration(s, addr->u.exec.args, &local_err);
2240     } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
2241         file_start_outgoing_migration(s, &addr->u.file, &local_err);
2242     } else {
2243         error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "uri",
2244                    "a valid migration protocol");
2245         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2246                           MIGRATION_STATUS_FAILED);
2247     }
2248 
2249     if (local_err) {
2250         if (!resume_requested) {
2251             yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2252         }
2253         migrate_fd_error(s, local_err);
2254         error_propagate(errp, local_err);
2255         return;
2256     }
2257 }
2258 
2259 void qmp_migrate_cancel(Error **errp)
2260 {
2261     migration_cancel(NULL);
2262 }
2263 
2264 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2265 {
2266     MigrationState *s = migrate_get_current();
2267     if (s->state != state) {
2268         error_setg(errp,  "Migration not in expected state: %s",
2269                    MigrationStatus_str(s->state));
2270         return;
2271     }
2272     qemu_sem_post(&s->pause_sem);
2273 }
2274 
2275 int migration_rp_wait(MigrationState *s)
2276 {
2277     /* If migration has failure already, ignore the wait */
2278     if (migrate_has_error(s)) {
2279         return -1;
2280     }
2281 
2282     qemu_sem_wait(&s->rp_state.rp_sem);
2283 
2284     /* After wait, double check that there's no failure */
2285     if (migrate_has_error(s)) {
2286         return -1;
2287     }
2288 
2289     return 0;
2290 }
2291 
2292 void migration_rp_kick(MigrationState *s)
2293 {
2294     qemu_sem_post(&s->rp_state.rp_sem);
2295 }
2296 
2297 static struct rp_cmd_args {
2298     ssize_t     len; /* -1 = variable */
2299     const char *name;
2300 } rp_cmd_args[] = {
2301     [MIG_RP_MSG_INVALID]        = { .len = -1, .name = "INVALID" },
2302     [MIG_RP_MSG_SHUT]           = { .len =  4, .name = "SHUT" },
2303     [MIG_RP_MSG_PONG]           = { .len =  4, .name = "PONG" },
2304     [MIG_RP_MSG_REQ_PAGES]      = { .len = 12, .name = "REQ_PAGES" },
2305     [MIG_RP_MSG_REQ_PAGES_ID]   = { .len = -1, .name = "REQ_PAGES_ID" },
2306     [MIG_RP_MSG_RECV_BITMAP]    = { .len = -1, .name = "RECV_BITMAP" },
2307     [MIG_RP_MSG_RESUME_ACK]     = { .len =  4, .name = "RESUME_ACK" },
2308     [MIG_RP_MSG_SWITCHOVER_ACK] = { .len =  0, .name = "SWITCHOVER_ACK" },
2309     [MIG_RP_MSG_MAX]            = { .len = -1, .name = "MAX" },
2310 };
2311 
2312 /*
2313  * Process a request for pages received on the return path,
2314  * We're allowed to send more than requested (e.g. to round to our page size)
2315  * and we don't need to send pages that have already been sent.
2316  */
2317 static void
2318 migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2319                             ram_addr_t start, size_t len, Error **errp)
2320 {
2321     long our_host_ps = qemu_real_host_page_size();
2322 
2323     trace_migrate_handle_rp_req_pages(rbname, start, len);
2324 
2325     /*
2326      * Since we currently insist on matching page sizes, just sanity check
2327      * we're being asked for whole host pages.
2328      */
2329     if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
2330         !QEMU_IS_ALIGNED(len, our_host_ps)) {
2331         error_setg(errp, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
2332                    RAM_ADDR_FMT " len: %zd", start, len);
2333         return;
2334     }
2335 
2336     ram_save_queue_pages(rbname, start, len, errp);
2337 }
2338 
2339 static bool migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name,
2340                                           Error **errp)
2341 {
2342     RAMBlock *block = qemu_ram_block_by_name(block_name);
2343 
2344     if (!block) {
2345         error_setg(errp, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
2346                    block_name);
2347         return false;
2348     }
2349 
2350     /* Fetch the received bitmap and refresh the dirty bitmap */
2351     return ram_dirty_bitmap_reload(s, block, errp);
2352 }
2353 
2354 static bool migrate_handle_rp_resume_ack(MigrationState *s,
2355                                          uint32_t value, Error **errp)
2356 {
2357     trace_source_return_path_thread_resume_ack(value);
2358 
2359     if (value != MIGRATION_RESUME_ACK_VALUE) {
2360         error_setg(errp, "illegal resume_ack value %"PRIu32, value);
2361         return false;
2362     }
2363 
2364     /* Now both sides are active. */
2365     migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2366                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2367 
2368     /* Notify send thread that time to continue send pages */
2369     migration_rp_kick(s);
2370 
2371     return true;
2372 }
2373 
2374 /*
2375  * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2376  * existed) in a safe way.
2377  */
2378 static void migration_release_dst_files(MigrationState *ms)
2379 {
2380     QEMUFile *file = NULL;
2381 
2382     WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2383         /*
2384          * Reset the from_dst_file pointer first before releasing it, as we
2385          * can't block within lock section
2386          */
2387         file = ms->rp_state.from_dst_file;
2388         ms->rp_state.from_dst_file = NULL;
2389     }
2390 
2391     /*
2392      * Do the same to postcopy fast path socket too if there is.  No
2393      * locking needed because this qemufile should only be managed by
2394      * return path thread.
2395      */
2396     if (ms->postcopy_qemufile_src) {
2397         migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
2398         qemu_file_shutdown(ms->postcopy_qemufile_src);
2399         qemu_fclose(ms->postcopy_qemufile_src);
2400         ms->postcopy_qemufile_src = NULL;
2401     }
2402 
2403     qemu_fclose(file);
2404 }
2405 
2406 /*
2407  * Handles messages sent on the return path towards the source VM
2408  *
2409  */
2410 static void *source_return_path_thread(void *opaque)
2411 {
2412     MigrationState *ms = opaque;
2413     QEMUFile *rp = ms->rp_state.from_dst_file;
2414     uint16_t header_len, header_type;
2415     uint8_t buf[512];
2416     uint32_t tmp32, sibling_error;
2417     ram_addr_t start = 0; /* =0 to silence warning */
2418     size_t  len = 0, expected_len;
2419     Error *err = NULL;
2420     int res;
2421 
2422     trace_source_return_path_thread_entry();
2423     rcu_register_thread();
2424 
2425     while (migration_is_running()) {
2426         trace_source_return_path_thread_loop_top();
2427 
2428         header_type = qemu_get_be16(rp);
2429         header_len = qemu_get_be16(rp);
2430 
2431         if (qemu_file_get_error(rp)) {
2432             qemu_file_get_error_obj(rp, &err);
2433             goto out;
2434         }
2435 
2436         if (header_type >= MIG_RP_MSG_MAX ||
2437             header_type == MIG_RP_MSG_INVALID) {
2438             error_setg(&err, "Received invalid message 0x%04x length 0x%04x",
2439                        header_type, header_len);
2440             goto out;
2441         }
2442 
2443         if ((rp_cmd_args[header_type].len != -1 &&
2444             header_len != rp_cmd_args[header_type].len) ||
2445             header_len > sizeof(buf)) {
2446             error_setg(&err, "Received '%s' message (0x%04x) with"
2447                        "incorrect length %d expecting %zu",
2448                        rp_cmd_args[header_type].name, header_type, header_len,
2449                        (size_t)rp_cmd_args[header_type].len);
2450             goto out;
2451         }
2452 
2453         /* We know we've got a valid header by this point */
2454         res = qemu_get_buffer(rp, buf, header_len);
2455         if (res != header_len) {
2456             error_setg(&err, "Failed reading data for message 0x%04x"
2457                        " read %d expected %d",
2458                        header_type, res, header_len);
2459             goto out;
2460         }
2461 
2462         /* OK, we have the message and the data */
2463         switch (header_type) {
2464         case MIG_RP_MSG_SHUT:
2465             sibling_error = ldl_be_p(buf);
2466             trace_source_return_path_thread_shut(sibling_error);
2467             if (sibling_error) {
2468                 error_setg(&err, "Sibling indicated error %d", sibling_error);
2469             }
2470             /*
2471              * We'll let the main thread deal with closing the RP
2472              * we could do a shutdown(2) on it, but we're the only user
2473              * anyway, so there's nothing gained.
2474              */
2475             goto out;
2476 
2477         case MIG_RP_MSG_PONG:
2478             tmp32 = ldl_be_p(buf);
2479             trace_source_return_path_thread_pong(tmp32);
2480             qemu_sem_post(&ms->rp_state.rp_pong_acks);
2481             break;
2482 
2483         case MIG_RP_MSG_REQ_PAGES:
2484             start = ldq_be_p(buf);
2485             len = ldl_be_p(buf + 8);
2486             migrate_handle_rp_req_pages(ms, NULL, start, len, &err);
2487             if (err) {
2488                 goto out;
2489             }
2490             break;
2491 
2492         case MIG_RP_MSG_REQ_PAGES_ID:
2493             expected_len = 12 + 1; /* header + termination */
2494 
2495             if (header_len >= expected_len) {
2496                 start = ldq_be_p(buf);
2497                 len = ldl_be_p(buf + 8);
2498                 /* Now we expect an idstr */
2499                 tmp32 = buf[12]; /* Length of the following idstr */
2500                 buf[13 + tmp32] = '\0';
2501                 expected_len += tmp32;
2502             }
2503             if (header_len != expected_len) {
2504                 error_setg(&err, "Req_Page_id with length %d expecting %zd",
2505                            header_len, expected_len);
2506                 goto out;
2507             }
2508             migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len,
2509                                         &err);
2510             if (err) {
2511                 goto out;
2512             }
2513             break;
2514 
2515         case MIG_RP_MSG_RECV_BITMAP:
2516             if (header_len < 1) {
2517                 error_setg(&err, "MIG_RP_MSG_RECV_BITMAP missing block name");
2518                 goto out;
2519             }
2520             /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2521             buf[buf[0] + 1] = '\0';
2522             if (!migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1), &err)) {
2523                 goto out;
2524             }
2525             break;
2526 
2527         case MIG_RP_MSG_RESUME_ACK:
2528             tmp32 = ldl_be_p(buf);
2529             if (!migrate_handle_rp_resume_ack(ms, tmp32, &err)) {
2530                 goto out;
2531             }
2532             break;
2533 
2534         case MIG_RP_MSG_SWITCHOVER_ACK:
2535             ms->switchover_acked = true;
2536             trace_source_return_path_thread_switchover_acked();
2537             break;
2538 
2539         default:
2540             break;
2541         }
2542     }
2543 
2544 out:
2545     if (err) {
2546         migrate_set_error(ms, err);
2547         error_free(err);
2548         trace_source_return_path_thread_bad_end();
2549     }
2550 
2551     if (ms->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2552         /*
2553          * this will be extremely unlikely: that we got yet another network
2554          * issue during recovering of the 1st network failure.. during this
2555          * period the main migration thread can be waiting on rp_sem for
2556          * this thread to sync with the other side.
2557          *
2558          * When this happens, explicitly kick the migration thread out of
2559          * RECOVER stage and back to PAUSED, so the admin can try
2560          * everything again.
2561          */
2562         migration_rp_kick(ms);
2563     }
2564 
2565     trace_source_return_path_thread_end();
2566     rcu_unregister_thread();
2567 
2568     return NULL;
2569 }
2570 
2571 static int open_return_path_on_source(MigrationState *ms)
2572 {
2573     ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2574     if (!ms->rp_state.from_dst_file) {
2575         return -1;
2576     }
2577 
2578     trace_open_return_path_on_source();
2579 
2580     qemu_thread_create(&ms->rp_state.rp_thread, MIGRATION_THREAD_SRC_RETURN,
2581                        source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2582     ms->rp_state.rp_thread_created = true;
2583 
2584     trace_open_return_path_on_source_continue();
2585 
2586     return 0;
2587 }
2588 
2589 /* Return true if error detected, or false otherwise */
2590 static bool close_return_path_on_source(MigrationState *ms)
2591 {
2592     if (!ms->rp_state.rp_thread_created) {
2593         return false;
2594     }
2595 
2596     trace_migration_return_path_end_before();
2597 
2598     /*
2599      * If this is a normal exit then the destination will send a SHUT
2600      * and the rp_thread will exit, however if there's an error we
2601      * need to cause it to exit. shutdown(2), if we have it, will
2602      * cause it to unblock if it's stuck waiting for the destination.
2603      */
2604     WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2605         if (migrate_has_error(ms) && ms->rp_state.from_dst_file) {
2606             qemu_file_shutdown(ms->rp_state.from_dst_file);
2607         }
2608     }
2609 
2610     qemu_thread_join(&ms->rp_state.rp_thread);
2611     ms->rp_state.rp_thread_created = false;
2612     migration_release_dst_files(ms);
2613     trace_migration_return_path_end_after();
2614 
2615     /* Return path will persist the error in MigrationState when quit */
2616     return migrate_has_error(ms);
2617 }
2618 
2619 static inline void
2620 migration_wait_main_channel(MigrationState *ms)
2621 {
2622     /* Wait until one PONG message received */
2623     qemu_sem_wait(&ms->rp_state.rp_pong_acks);
2624 }
2625 
2626 /*
2627  * Switch from normal iteration to postcopy
2628  * Returns non-0 on error
2629  */
2630 static int postcopy_start(MigrationState *ms, Error **errp)
2631 {
2632     int ret;
2633     QIOChannelBuffer *bioc;
2634     QEMUFile *fb;
2635 
2636     /*
2637      * Now we're 100% sure to switch to postcopy, so JSON writer won't be
2638      * useful anymore.  Free the resources early if it is there.  Clearing
2639      * the vmdesc also means any follow up vmstate_save()s will start to
2640      * skip all JSON operations, which can shrink postcopy downtime.
2641      */
2642     migration_cleanup_json_writer(ms);
2643 
2644     if (migrate_postcopy_preempt()) {
2645         migration_wait_main_channel(ms);
2646         if (postcopy_preempt_establish_channel(ms)) {
2647             migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
2648             error_setg(errp, "%s: Failed to establish preempt channel",
2649                        __func__);
2650             return -1;
2651         }
2652     }
2653 
2654     trace_postcopy_start();
2655     bql_lock();
2656     trace_postcopy_start_set_run();
2657 
2658     ret = migration_stop_vm(ms, RUN_STATE_FINISH_MIGRATE);
2659     if (ret < 0) {
2660         error_setg_errno(errp, -ret, "%s: Failed to stop the VM", __func__);
2661         goto fail;
2662     }
2663 
2664     if (!migration_switchover_start(ms, errp)) {
2665         goto fail;
2666     }
2667 
2668     /*
2669      * Cause any non-postcopiable, but iterative devices to
2670      * send out their final data.
2671      */
2672     ret = qemu_savevm_state_complete_precopy_iterable(ms->to_dst_file, true);
2673     if (ret) {
2674         error_setg(errp, "Postcopy save non-postcopiable iterables failed");
2675         goto fail;
2676     }
2677 
2678     /*
2679      * in Finish migrate and with the io-lock held everything should
2680      * be quiet, but we've potentially still got dirty pages and we
2681      * need to tell the destination to throw any pages it's already received
2682      * that are dirty
2683      */
2684     if (migrate_postcopy_ram()) {
2685         ram_postcopy_send_discard_bitmap(ms);
2686     }
2687 
2688     if (migrate_postcopy_ram()) {
2689         /* Ping just for debugging, helps line traces up */
2690         qemu_savevm_send_ping(ms->to_dst_file, 2);
2691     }
2692 
2693     /*
2694      * While loading the device state we may trigger page transfer
2695      * requests and the fd must be free to process those, and thus
2696      * the destination must read the whole device state off the fd before
2697      * it starts processing it.  Unfortunately the ad-hoc migration format
2698      * doesn't allow the destination to know the size to read without fully
2699      * parsing it through each devices load-state code (especially the open
2700      * coded devices that use get/put).
2701      * So we wrap the device state up in a package with a length at the start;
2702      * to do this we use a qemu_buf to hold the whole of the device state.
2703      */
2704     bioc = qio_channel_buffer_new(4096);
2705     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2706     fb = qemu_file_new_output(QIO_CHANNEL(bioc));
2707     object_unref(OBJECT(bioc));
2708 
2709     /*
2710      * Make sure the receiver can get incoming pages before we send the rest
2711      * of the state
2712      */
2713     qemu_savevm_send_postcopy_listen(fb);
2714 
2715     ret = qemu_savevm_state_complete_precopy_non_iterable(fb, true);
2716     if (ret) {
2717         error_setg(errp, "Postcopy save non-iterable device states failed");
2718         goto fail_closefb;
2719     }
2720 
2721     if (migrate_postcopy_ram()) {
2722         qemu_savevm_send_ping(fb, 3);
2723     }
2724 
2725     qemu_savevm_send_postcopy_run(fb);
2726 
2727     /* <><> end of stuff going into the package */
2728 
2729     /* Last point of recovery; as soon as we send the package the destination
2730      * can open devices and potentially start running.
2731      * Lets just check again we've not got any errors.
2732      */
2733     ret = qemu_file_get_error(ms->to_dst_file);
2734     if (ret) {
2735         error_setg(errp, "postcopy_start: Migration stream errored (pre package)");
2736         goto fail_closefb;
2737     }
2738 
2739     /* Now send that blob */
2740     if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2741         error_setg(errp, "%s: Failed to send packaged data", __func__);
2742         goto fail_closefb;
2743     }
2744     qemu_fclose(fb);
2745 
2746     /* Send a notify to give a chance for anything that needs to happen
2747      * at the transition to postcopy and after the device state; in particular
2748      * spice needs to trigger a transition now
2749      */
2750     migration_call_notifiers(ms, MIG_EVENT_PRECOPY_DONE, NULL);
2751 
2752     migration_downtime_end(ms);
2753 
2754     if (migrate_postcopy_ram()) {
2755         /*
2756          * Although this ping is just for debug, it could potentially be
2757          * used for getting a better measurement of downtime at the source.
2758          */
2759         qemu_savevm_send_ping(ms->to_dst_file, 4);
2760     }
2761 
2762     if (migrate_release_ram()) {
2763         ram_postcopy_migrated_memory_release(ms);
2764     }
2765 
2766     ret = qemu_file_get_error(ms->to_dst_file);
2767     if (ret) {
2768         error_setg_errno(errp, -ret, "postcopy_start: Migration stream error");
2769         goto fail;
2770     }
2771     trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2772 
2773     /*
2774      * Now postcopy officially started, switch to postcopy bandwidth that
2775      * user specified.
2776      */
2777     migration_rate_set(migrate_max_postcopy_bandwidth());
2778 
2779     /* Now, switchover looks all fine, switching to postcopy-active */
2780     migrate_set_state(&ms->state, MIGRATION_STATUS_DEVICE,
2781                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2782 
2783     bql_unlock();
2784 
2785     return ret;
2786 
2787 fail_closefb:
2788     qemu_fclose(fb);
2789 fail:
2790     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2791                           MIGRATION_STATUS_FAILED);
2792     migration_block_activate(NULL);
2793     migration_call_notifiers(ms, MIG_EVENT_PRECOPY_FAILED, NULL);
2794     bql_unlock();
2795     return -1;
2796 }
2797 
2798 /**
2799  * @migration_switchover_prepare: Start VM switchover procedure
2800  *
2801  * @s: The migration state object pointer
2802  *
2803  * Prepares for the switchover, depending on "pause-before-switchover"
2804  * capability.
2805  *
2806  * If cap set, state machine goes like:
2807  *   [postcopy-]active -> pre-switchover -> device
2808  *
2809  * If cap not set:
2810  *   [postcopy-]active -> device
2811  *
2812  * Returns: true on success, false on interruptions.
2813  */
2814 static bool migration_switchover_prepare(MigrationState *s)
2815 {
2816     /* Concurrent cancellation?  Quit */
2817     if (s->state == MIGRATION_STATUS_CANCELLING) {
2818         return false;
2819     }
2820 
2821     /*
2822      * No matter precopy or postcopy, since we still hold BQL it must not
2823      * change concurrently to CANCELLING, so it must be either ACTIVE or
2824      * POSTCOPY_ACTIVE.
2825      */
2826     assert(migration_is_active());
2827 
2828     /* If the pre stage not requested, directly switch to DEVICE */
2829     if (!migrate_pause_before_switchover()) {
2830         migrate_set_state(&s->state, s->state, MIGRATION_STATUS_DEVICE);
2831         return true;
2832     }
2833 
2834     /* Since leaving this state is not atomic with posting the semaphore
2835      * it's possible that someone could have issued multiple migrate_continue
2836      * and the semaphore is incorrectly positive at this point;
2837      * the docs say it's undefined to reinit a semaphore that's already
2838      * init'd, so use timedwait to eat up any existing posts.
2839      */
2840     while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2841         /* This block intentionally left blank */
2842     }
2843 
2844     /* Update [POSTCOPY_]ACTIVE to PRE_SWITCHOVER */
2845     migrate_set_state(&s->state, s->state, MIGRATION_STATUS_PRE_SWITCHOVER);
2846     bql_unlock();
2847 
2848     qemu_sem_wait(&s->pause_sem);
2849 
2850     bql_lock();
2851     /*
2852      * After BQL released and retaken, the state can be CANCELLING if it
2853      * happend during sem_wait().. Only change the state if it's still
2854      * pre-switchover.
2855      */
2856     migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2857                       MIGRATION_STATUS_DEVICE);
2858 
2859     return s->state == MIGRATION_STATUS_DEVICE;
2860 }
2861 
2862 static bool migration_switchover_start(MigrationState *s, Error **errp)
2863 {
2864     ERRP_GUARD();
2865 
2866     if (!migration_switchover_prepare(s)) {
2867         error_setg(errp, "Switchover is interrupted");
2868         return false;
2869     }
2870 
2871     /* Inactivate disks except in COLO */
2872     if (!migrate_colo()) {
2873         /*
2874          * Inactivate before sending QEMU_VM_EOF so that the
2875          * bdrv_activate_all() on the other end won't fail.
2876          */
2877         if (!migration_block_inactivate()) {
2878             error_setg(errp, "Block inactivate failed during switchover");
2879             return false;
2880         }
2881     }
2882 
2883     migration_rate_set(RATE_LIMIT_DISABLED);
2884 
2885     precopy_notify_complete();
2886 
2887     return true;
2888 }
2889 
2890 static int migration_completion_precopy(MigrationState *s)
2891 {
2892     int ret;
2893 
2894     bql_lock();
2895 
2896     if (!migrate_mode_is_cpr(s)) {
2897         ret = migration_stop_vm(s, RUN_STATE_FINISH_MIGRATE);
2898         if (ret < 0) {
2899             goto out_unlock;
2900         }
2901     }
2902 
2903     if (!migration_switchover_start(s, NULL)) {
2904         ret = -EFAULT;
2905         goto out_unlock;
2906     }
2907 
2908     ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false);
2909 out_unlock:
2910     bql_unlock();
2911     return ret;
2912 }
2913 
2914 static void migration_completion_postcopy(MigrationState *s)
2915 {
2916     trace_migration_completion_postcopy_end();
2917 
2918     bql_lock();
2919     qemu_savevm_state_complete_postcopy(s->to_dst_file);
2920     bql_unlock();
2921 
2922     /*
2923      * Shutdown the postcopy fast path thread.  This is only needed when dest
2924      * QEMU binary is old (7.1/7.2).  QEMU 8.0+ doesn't need this.
2925      */
2926     if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
2927         postcopy_preempt_shutdown_file(s);
2928     }
2929 
2930     trace_migration_completion_postcopy_end_after_complete();
2931 }
2932 
2933 /**
2934  * migration_completion: Used by migration_thread when there's not much left.
2935  *   The caller 'breaks' the loop when this returns.
2936  *
2937  * @s: Current migration state
2938  */
2939 static void migration_completion(MigrationState *s)
2940 {
2941     int ret = 0;
2942     Error *local_err = NULL;
2943 
2944     if (s->state == MIGRATION_STATUS_ACTIVE) {
2945         ret = migration_completion_precopy(s);
2946     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2947         migration_completion_postcopy(s);
2948     } else {
2949         ret = -1;
2950     }
2951 
2952     if (ret < 0) {
2953         goto fail;
2954     }
2955 
2956     if (close_return_path_on_source(s)) {
2957         goto fail;
2958     }
2959 
2960     if (qemu_file_get_error(s->to_dst_file)) {
2961         trace_migration_completion_file_err();
2962         goto fail;
2963     }
2964 
2965     if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) {
2966         /* COLO does not support postcopy */
2967         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
2968                           MIGRATION_STATUS_COLO);
2969     } else {
2970         migration_completion_end(s);
2971     }
2972 
2973     return;
2974 
2975 fail:
2976     if (qemu_file_get_error_obj(s->to_dst_file, &local_err)) {
2977         migrate_set_error(s, local_err);
2978         error_free(local_err);
2979     } else if (ret) {
2980         error_setg_errno(&local_err, -ret, "Error in migration completion");
2981         migrate_set_error(s, local_err);
2982         error_free(local_err);
2983     }
2984 
2985     migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
2986 }
2987 
2988 /**
2989  * bg_migration_completion: Used by bg_migration_thread when after all the
2990  *   RAM has been saved. The caller 'breaks' the loop when this returns.
2991  *
2992  * @s: Current migration state
2993  */
2994 static void bg_migration_completion(MigrationState *s)
2995 {
2996     int current_active_state = s->state;
2997 
2998     if (s->state == MIGRATION_STATUS_ACTIVE) {
2999         /*
3000          * By this moment we have RAM content saved into the migration stream.
3001          * The next step is to flush the non-RAM content (device state)
3002          * right after the ram content. The device state has been stored into
3003          * the temporary buffer before RAM saving started.
3004          */
3005         qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
3006         qemu_fflush(s->to_dst_file);
3007     } else if (s->state == MIGRATION_STATUS_CANCELLING) {
3008         goto fail;
3009     }
3010 
3011     if (qemu_file_get_error(s->to_dst_file)) {
3012         trace_migration_completion_file_err();
3013         goto fail;
3014     }
3015 
3016     migration_completion_end(s);
3017     return;
3018 
3019 fail:
3020     migrate_set_state(&s->state, current_active_state,
3021                       MIGRATION_STATUS_FAILED);
3022 }
3023 
3024 typedef enum MigThrError {
3025     /* No error detected */
3026     MIG_THR_ERR_NONE = 0,
3027     /* Detected error, but resumed successfully */
3028     MIG_THR_ERR_RECOVERED = 1,
3029     /* Detected fatal error, need to exit */
3030     MIG_THR_ERR_FATAL = 2,
3031 } MigThrError;
3032 
3033 static int postcopy_resume_handshake(MigrationState *s)
3034 {
3035     qemu_savevm_send_postcopy_resume(s->to_dst_file);
3036 
3037     while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3038         if (migration_rp_wait(s)) {
3039             return -1;
3040         }
3041     }
3042 
3043     if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3044         return 0;
3045     }
3046 
3047     return -1;
3048 }
3049 
3050 /* Return zero if success, or <0 for error */
3051 static int postcopy_do_resume(MigrationState *s)
3052 {
3053     int ret;
3054 
3055     /*
3056      * Call all the resume_prepare() hooks, so that modules can be
3057      * ready for the migration resume.
3058      */
3059     ret = qemu_savevm_state_resume_prepare(s);
3060     if (ret) {
3061         error_report("%s: resume_prepare() failure detected: %d",
3062                      __func__, ret);
3063         return ret;
3064     }
3065 
3066     /*
3067      * If preempt is enabled, re-establish the preempt channel.  Note that
3068      * we do it after resume prepare to make sure the main channel will be
3069      * created before the preempt channel.  E.g. with weak network, the
3070      * dest QEMU may get messed up with the preempt and main channels on
3071      * the order of connection setup.  This guarantees the correct order.
3072      */
3073     ret = postcopy_preempt_establish_channel(s);
3074     if (ret) {
3075         error_report("%s: postcopy_preempt_establish_channel(): %d",
3076                      __func__, ret);
3077         return ret;
3078     }
3079 
3080     /*
3081      * Last handshake with destination on the resume (destination will
3082      * switch to postcopy-active afterwards)
3083      */
3084     ret = postcopy_resume_handshake(s);
3085     if (ret) {
3086         error_report("%s: handshake failed: %d", __func__, ret);
3087         return ret;
3088     }
3089 
3090     return 0;
3091 }
3092 
3093 /*
3094  * We don't return until we are in a safe state to continue current
3095  * postcopy migration.  Returns MIG_THR_ERR_RECOVERED if recovered, or
3096  * MIG_THR_ERR_FATAL if unrecovery failure happened.
3097  */
3098 static MigThrError postcopy_pause(MigrationState *s)
3099 {
3100     assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3101 
3102     while (true) {
3103         QEMUFile *file;
3104 
3105         /*
3106          * We're already pausing, so ignore any errors on the return
3107          * path and just wait for the thread to finish. It will be
3108          * re-created when we resume.
3109          */
3110         close_return_path_on_source(s);
3111 
3112         /*
3113          * Current channel is possibly broken. Release it.  Note that this is
3114          * guaranteed even without lock because to_dst_file should only be
3115          * modified by the migration thread.  That also guarantees that the
3116          * unregister of yank is safe too without the lock.  It should be safe
3117          * even to be within the qemu_file_lock, but we didn't do that to avoid
3118          * taking more mutex (yank_lock) within qemu_file_lock.  TL;DR: we make
3119          * the qemu_file_lock critical section as small as possible.
3120          */
3121         assert(s->to_dst_file);
3122         migration_ioc_unregister_yank_from_file(s->to_dst_file);
3123         qemu_mutex_lock(&s->qemu_file_lock);
3124         file = s->to_dst_file;
3125         s->to_dst_file = NULL;
3126         qemu_mutex_unlock(&s->qemu_file_lock);
3127 
3128         qemu_file_shutdown(file);
3129         qemu_fclose(file);
3130 
3131         migrate_set_state(&s->state, s->state,
3132                           MIGRATION_STATUS_POSTCOPY_PAUSED);
3133 
3134         error_report("Detected IO failure for postcopy. "
3135                      "Migration paused.");
3136 
3137         /*
3138          * We wait until things fixed up. Then someone will setup the
3139          * status back for us.
3140          */
3141         do {
3142             qemu_sem_wait(&s->postcopy_pause_sem);
3143         } while (postcopy_is_paused(s->state));
3144 
3145         if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3146             /* Woken up by a recover procedure. Give it a shot */
3147 
3148             /* Do the resume logic */
3149             if (postcopy_do_resume(s) == 0) {
3150                 /* Let's continue! */
3151                 trace_postcopy_pause_continued();
3152                 return MIG_THR_ERR_RECOVERED;
3153             } else {
3154                 /*
3155                  * Something wrong happened during the recovery, let's
3156                  * pause again. Pause is always better than throwing
3157                  * data away.
3158                  */
3159                 continue;
3160             }
3161         } else {
3162             /* This is not right... Time to quit. */
3163             return MIG_THR_ERR_FATAL;
3164         }
3165     }
3166 }
3167 
3168 void migration_file_set_error(int ret, Error *err)
3169 {
3170     MigrationState *s = current_migration;
3171 
3172     WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
3173         if (s->to_dst_file) {
3174             qemu_file_set_error_obj(s->to_dst_file, ret, err);
3175         } else if (err) {
3176             error_report_err(err);
3177         }
3178     }
3179 }
3180 
3181 static MigThrError migration_detect_error(MigrationState *s)
3182 {
3183     int ret;
3184     int state = s->state;
3185     Error *local_error = NULL;
3186 
3187     if (state == MIGRATION_STATUS_CANCELLING ||
3188         state == MIGRATION_STATUS_CANCELLED) {
3189         /* End the migration, but don't set the state to failed */
3190         return MIG_THR_ERR_FATAL;
3191     }
3192 
3193     /*
3194      * Try to detect any file errors.  Note that postcopy_qemufile_src will
3195      * be NULL when postcopy preempt is not enabled.
3196      */
3197     ret = qemu_file_get_error_obj_any(s->to_dst_file,
3198                                       s->postcopy_qemufile_src,
3199                                       &local_error);
3200     if (!ret) {
3201         /* Everything is fine */
3202         assert(!local_error);
3203         return MIG_THR_ERR_NONE;
3204     }
3205 
3206     if (local_error) {
3207         migrate_set_error(s, local_error);
3208         error_free(local_error);
3209     }
3210 
3211     if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
3212         /*
3213          * For postcopy, we allow the network to be down for a
3214          * while. After that, it can be continued by a
3215          * recovery phase.
3216          */
3217         return postcopy_pause(s);
3218     } else {
3219         /*
3220          * For precopy (or postcopy with error outside IO), we fail
3221          * with no time.
3222          */
3223         migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3224         trace_migration_thread_file_err();
3225 
3226         /* Time to stop the migration, now. */
3227         return MIG_THR_ERR_FATAL;
3228     }
3229 }
3230 
3231 static void migration_completion_end(MigrationState *s)
3232 {
3233     uint64_t bytes = migration_transferred_bytes();
3234     int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3235     int64_t transfer_time;
3236 
3237     /*
3238      * Take the BQL here so that query-migrate on the QMP thread sees:
3239      * - atomic update of s->total_time and s->mbps;
3240      * - correct ordering of s->mbps update vs. s->state;
3241      */
3242     bql_lock();
3243     migration_downtime_end(s);
3244     s->total_time = end_time - s->start_time;
3245     transfer_time = s->total_time - s->setup_time;
3246     if (transfer_time) {
3247         s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3248     }
3249 
3250     migrate_set_state(&s->state, s->state,
3251                       MIGRATION_STATUS_COMPLETED);
3252     bql_unlock();
3253 }
3254 
3255 static void update_iteration_initial_status(MigrationState *s)
3256 {
3257     /*
3258      * Update these three fields at the same time to avoid mismatch info lead
3259      * wrong speed calculation.
3260      */
3261     s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3262     s->iteration_initial_bytes = migration_transferred_bytes();
3263     s->iteration_initial_pages = ram_get_total_transferred_pages();
3264 }
3265 
3266 static void migration_update_counters(MigrationState *s,
3267                                       int64_t current_time)
3268 {
3269     uint64_t transferred, transferred_pages, time_spent;
3270     uint64_t current_bytes; /* bytes transferred since the beginning */
3271     uint64_t switchover_bw;
3272     /* Expected bandwidth when switching over to destination QEMU */
3273     double expected_bw_per_ms;
3274     double bandwidth;
3275 
3276     if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3277         return;
3278     }
3279 
3280     switchover_bw = migrate_avail_switchover_bandwidth();
3281     current_bytes = migration_transferred_bytes();
3282     transferred = current_bytes - s->iteration_initial_bytes;
3283     time_spent = current_time - s->iteration_start_time;
3284     bandwidth = (double)transferred / time_spent;
3285 
3286     if (switchover_bw) {
3287         /*
3288          * If the user specified a switchover bandwidth, let's trust the
3289          * user so that can be more accurate than what we estimated.
3290          */
3291         expected_bw_per_ms = switchover_bw / 1000;
3292     } else {
3293         /* If the user doesn't specify bandwidth, we use the estimated */
3294         expected_bw_per_ms = bandwidth;
3295     }
3296 
3297     s->threshold_size = expected_bw_per_ms * migrate_downtime_limit();
3298 
3299     s->mbps = (((double) transferred * 8.0) /
3300                ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3301 
3302     transferred_pages = ram_get_total_transferred_pages() -
3303                             s->iteration_initial_pages;
3304     s->pages_per_second = (double) transferred_pages /
3305                              (((double) time_spent / 1000.0));
3306 
3307     /*
3308      * if we haven't sent anything, we don't want to
3309      * recalculate. 10000 is a small enough number for our purposes
3310      */
3311     if (stat64_get(&mig_stats.dirty_pages_rate) &&
3312         transferred > 10000) {
3313         s->expected_downtime =
3314             stat64_get(&mig_stats.dirty_bytes_last_sync) / expected_bw_per_ms;
3315     }
3316 
3317     migration_rate_reset();
3318 
3319     update_iteration_initial_status(s);
3320 
3321     trace_migrate_transferred(transferred, time_spent,
3322                               /* Both in unit bytes/ms */
3323                               bandwidth, switchover_bw / 1000,
3324                               s->threshold_size);
3325 }
3326 
3327 static bool migration_can_switchover(MigrationState *s)
3328 {
3329     if (!migrate_switchover_ack()) {
3330         return true;
3331     }
3332 
3333     /* No reason to wait for switchover ACK if VM is stopped */
3334     if (!runstate_is_running()) {
3335         return true;
3336     }
3337 
3338     return s->switchover_acked;
3339 }
3340 
3341 /* Migration thread iteration status */
3342 typedef enum {
3343     MIG_ITERATE_RESUME,         /* Resume current iteration */
3344     MIG_ITERATE_SKIP,           /* Skip current iteration */
3345     MIG_ITERATE_BREAK,          /* Break the loop */
3346 } MigIterateState;
3347 
3348 /*
3349  * Return true if continue to the next iteration directly, false
3350  * otherwise.
3351  */
3352 static MigIterateState migration_iteration_run(MigrationState *s)
3353 {
3354     uint64_t must_precopy, can_postcopy, pending_size;
3355     Error *local_err = NULL;
3356     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3357     bool can_switchover = migration_can_switchover(s);
3358 
3359     qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
3360     pending_size = must_precopy + can_postcopy;
3361     trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
3362 
3363     if (pending_size < s->threshold_size) {
3364         qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
3365         pending_size = must_precopy + can_postcopy;
3366         trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy);
3367     }
3368 
3369     if ((!pending_size || pending_size < s->threshold_size) && can_switchover) {
3370         trace_migration_thread_low_pending(pending_size);
3371         migration_completion(s);
3372         return MIG_ITERATE_BREAK;
3373     }
3374 
3375     /* Still a significant amount to transfer */
3376     if (!in_postcopy && must_precopy <= s->threshold_size && can_switchover &&
3377         qatomic_read(&s->start_postcopy)) {
3378         if (postcopy_start(s, &local_err)) {
3379             migrate_set_error(s, local_err);
3380             error_report_err(local_err);
3381         }
3382         return MIG_ITERATE_SKIP;
3383     }
3384 
3385     /* Just another iteration step */
3386     qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3387     return MIG_ITERATE_RESUME;
3388 }
3389 
3390 static void migration_iteration_finish(MigrationState *s)
3391 {
3392     bql_lock();
3393 
3394     /*
3395      * If we enabled cpu throttling for auto-converge, turn it off.
3396      * Stopping CPU throttle should be serialized by BQL to avoid
3397      * racing for the throttle_dirty_sync_timer.
3398      */
3399     if (migrate_auto_converge()) {
3400         cpu_throttle_stop();
3401     }
3402 
3403     switch (s->state) {
3404     case MIGRATION_STATUS_COMPLETED:
3405         runstate_set(RUN_STATE_POSTMIGRATE);
3406         break;
3407     case MIGRATION_STATUS_COLO:
3408         assert(migrate_colo());
3409         migrate_start_colo_process(s);
3410         s->vm_old_state = RUN_STATE_RUNNING;
3411         /* Fallthrough */
3412     case MIGRATION_STATUS_FAILED:
3413     case MIGRATION_STATUS_CANCELLED:
3414     case MIGRATION_STATUS_CANCELLING:
3415         /*
3416          * Re-activate the block drives if they're inactivated.  Note, COLO
3417          * shouldn't use block_active at all, so it should be no-op there.
3418          */
3419         migration_block_activate(NULL);
3420         if (runstate_is_live(s->vm_old_state)) {
3421             if (!runstate_check(RUN_STATE_SHUTDOWN)) {
3422                 vm_start();
3423             }
3424         } else {
3425             if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3426                 runstate_set(s->vm_old_state);
3427             }
3428         }
3429         break;
3430 
3431     default:
3432         /* Should not reach here, but if so, forgive the VM. */
3433         error_report("%s: Unknown ending state %d", __func__, s->state);
3434         break;
3435     }
3436 
3437     migration_bh_schedule(migrate_fd_cleanup_bh, s);
3438     bql_unlock();
3439 }
3440 
3441 static void bg_migration_iteration_finish(MigrationState *s)
3442 {
3443     /*
3444      * Stop tracking RAM writes - un-protect memory, un-register UFFD
3445      * memory ranges, flush kernel wait queues and wake up threads
3446      * waiting for write fault to be resolved.
3447      */
3448     ram_write_tracking_stop();
3449 
3450     bql_lock();
3451     switch (s->state) {
3452     case MIGRATION_STATUS_COMPLETED:
3453     case MIGRATION_STATUS_ACTIVE:
3454     case MIGRATION_STATUS_FAILED:
3455     case MIGRATION_STATUS_CANCELLED:
3456     case MIGRATION_STATUS_CANCELLING:
3457         break;
3458 
3459     default:
3460         /* Should not reach here, but if so, forgive the VM. */
3461         error_report("%s: Unknown ending state %d", __func__, s->state);
3462         break;
3463     }
3464 
3465     migration_bh_schedule(migrate_fd_cleanup_bh, s);
3466     bql_unlock();
3467 }
3468 
3469 /*
3470  * Return true if continue to the next iteration directly, false
3471  * otherwise.
3472  */
3473 static MigIterateState bg_migration_iteration_run(MigrationState *s)
3474 {
3475     int res;
3476 
3477     res = qemu_savevm_state_iterate(s->to_dst_file, false);
3478     if (res > 0) {
3479         bg_migration_completion(s);
3480         return MIG_ITERATE_BREAK;
3481     }
3482 
3483     return MIG_ITERATE_RESUME;
3484 }
3485 
3486 void migration_make_urgent_request(void)
3487 {
3488     qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3489 }
3490 
3491 void migration_consume_urgent_request(void)
3492 {
3493     qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3494 }
3495 
3496 /* Returns true if the rate limiting was broken by an urgent request */
3497 bool migration_rate_limit(void)
3498 {
3499     int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3500     MigrationState *s = migrate_get_current();
3501 
3502     bool urgent = false;
3503     migration_update_counters(s, now);
3504     if (migration_rate_exceeded(s->to_dst_file)) {
3505 
3506         if (qemu_file_get_error(s->to_dst_file)) {
3507             return false;
3508         }
3509         /*
3510          * Wait for a delay to do rate limiting OR
3511          * something urgent to post the semaphore.
3512          */
3513         int ms = s->iteration_start_time + BUFFER_DELAY - now;
3514         trace_migration_rate_limit_pre(ms);
3515         if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3516             /*
3517              * We were woken by one or more urgent things but
3518              * the timedwait will have consumed one of them.
3519              * The service routine for the urgent wake will dec
3520              * the semaphore itself for each item it consumes,
3521              * so add this one we just eat back.
3522              */
3523             qemu_sem_post(&s->rate_limit_sem);
3524             urgent = true;
3525         }
3526         trace_migration_rate_limit_post(urgent);
3527     }
3528     return urgent;
3529 }
3530 
3531 /*
3532  * if failover devices are present, wait they are completely
3533  * unplugged
3534  */
3535 
3536 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
3537                                     int new_state)
3538 {
3539     if (qemu_savevm_state_guest_unplug_pending()) {
3540         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
3541 
3542         while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3543                qemu_savevm_state_guest_unplug_pending()) {
3544             qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3545         }
3546         if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
3547             int timeout = 120; /* 30 seconds */
3548             /*
3549              * migration has been canceled
3550              * but as we have started an unplug we must wait the end
3551              * to be able to plug back the card
3552              */
3553             while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
3554                 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3555             }
3556             if (qemu_savevm_state_guest_unplug_pending() &&
3557                 !qtest_enabled()) {
3558                 warn_report("migration: partially unplugged device on "
3559                             "failure");
3560             }
3561         }
3562 
3563         migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
3564     } else {
3565         migrate_set_state(&s->state, old_state, new_state);
3566     }
3567 }
3568 
3569 /*
3570  * Master migration thread on the source VM.
3571  * It drives the migration and pumps the data down the outgoing channel.
3572  */
3573 static void *migration_thread(void *opaque)
3574 {
3575     MigrationState *s = opaque;
3576     MigrationThread *thread = NULL;
3577     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3578     MigThrError thr_error;
3579     bool urgent = false;
3580     Error *local_err = NULL;
3581     int ret;
3582 
3583     thread = migration_threads_add(MIGRATION_THREAD_SRC_MAIN,
3584                                    qemu_get_thread_id());
3585 
3586     rcu_register_thread();
3587 
3588     update_iteration_initial_status(s);
3589 
3590     if (!multifd_send_setup()) {
3591         goto out;
3592     }
3593 
3594     bql_lock();
3595     qemu_savevm_state_header(s->to_dst_file);
3596     bql_unlock();
3597 
3598     /*
3599      * If we opened the return path, we need to make sure dst has it
3600      * opened as well.
3601      */
3602     if (s->rp_state.rp_thread_created) {
3603         /* Now tell the dest that it should open its end so it can reply */
3604         qemu_savevm_send_open_return_path(s->to_dst_file);
3605 
3606         /* And do a ping that will make stuff easier to debug */
3607         qemu_savevm_send_ping(s->to_dst_file, 1);
3608     }
3609 
3610     if (migrate_postcopy()) {
3611         /*
3612          * Tell the destination that we *might* want to do postcopy later;
3613          * if the other end can't do postcopy it should fail now, nice and
3614          * early.
3615          */
3616         qemu_savevm_send_postcopy_advise(s->to_dst_file);
3617     }
3618 
3619     if (migrate_colo()) {
3620         /* Notify migration destination that we enable COLO */
3621         qemu_savevm_send_colo_enable(s->to_dst_file);
3622     }
3623 
3624     if (migrate_auto_converge()) {
3625         /* Start RAMBlock dirty bitmap sync timer */
3626         cpu_throttle_dirty_sync_timer(true);
3627     }
3628 
3629     bql_lock();
3630     ret = qemu_savevm_state_setup(s->to_dst_file, &local_err);
3631     bql_unlock();
3632 
3633     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3634                                MIGRATION_STATUS_ACTIVE);
3635 
3636     /*
3637      * Handle SETUP failures after waiting for virtio-net-failover
3638      * devices to unplug. This to preserve migration state transitions.
3639      */
3640     if (ret) {
3641         migrate_set_error(s, local_err);
3642         error_free(local_err);
3643         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3644                           MIGRATION_STATUS_FAILED);
3645         goto out;
3646     }
3647 
3648     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3649 
3650     trace_migration_thread_setup_complete();
3651 
3652     while (migration_is_active()) {
3653         if (urgent || !migration_rate_exceeded(s->to_dst_file)) {
3654             MigIterateState iter_state = migration_iteration_run(s);
3655             if (iter_state == MIG_ITERATE_SKIP) {
3656                 continue;
3657             } else if (iter_state == MIG_ITERATE_BREAK) {
3658                 break;
3659             }
3660         }
3661 
3662         /*
3663          * Try to detect any kind of failures, and see whether we
3664          * should stop the migration now.
3665          */
3666         thr_error = migration_detect_error(s);
3667         if (thr_error == MIG_THR_ERR_FATAL) {
3668             /* Stop migration */
3669             break;
3670         } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3671             /*
3672              * Just recovered from a e.g. network failure, reset all
3673              * the local variables. This is important to avoid
3674              * breaking transferred_bytes and bandwidth calculation
3675              */
3676             update_iteration_initial_status(s);
3677         }
3678 
3679         urgent = migration_rate_limit();
3680     }
3681 
3682 out:
3683     trace_migration_thread_after_loop();
3684     migration_iteration_finish(s);
3685     object_unref(OBJECT(s));
3686     rcu_unregister_thread();
3687     migration_threads_remove(thread);
3688     return NULL;
3689 }
3690 
3691 static void bg_migration_vm_start_bh(void *opaque)
3692 {
3693     MigrationState *s = opaque;
3694 
3695     vm_resume(s->vm_old_state);
3696     migration_downtime_end(s);
3697 }
3698 
3699 /**
3700  * Background snapshot thread, based on live migration code.
3701  * This is an alternative implementation of live migration mechanism
3702  * introduced specifically to support background snapshots.
3703  *
3704  * It takes advantage of userfault_fd write protection mechanism introduced
3705  * in v5.7 kernel. Compared to existing dirty page logging migration much
3706  * lesser stream traffic is produced resulting in smaller snapshot images,
3707  * simply cause of no page duplicates can get into the stream.
3708  *
3709  * Another key point is that generated vmstate stream reflects machine state
3710  * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3711  * mechanism, which effectively results in that saved snapshot is the state of VM
3712  * at the end of the process.
3713  */
3714 static void *bg_migration_thread(void *opaque)
3715 {
3716     MigrationState *s = opaque;
3717     int64_t setup_start;
3718     MigThrError thr_error;
3719     QEMUFile *fb;
3720     bool early_fail = true;
3721     Error *local_err = NULL;
3722     int ret;
3723 
3724     rcu_register_thread();
3725 
3726     migration_rate_set(RATE_LIMIT_DISABLED);
3727 
3728     setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3729     /*
3730      * We want to save vmstate for the moment when migration has been
3731      * initiated but also we want to save RAM content while VM is running.
3732      * The RAM content should appear first in the vmstate. So, we first
3733      * stash the non-RAM part of the vmstate to the temporary buffer,
3734      * then write RAM part of the vmstate to the migration stream
3735      * with vCPUs running and, finally, write stashed non-RAM part of
3736      * the vmstate from the buffer to the migration stream.
3737      */
3738     s->bioc = qio_channel_buffer_new(512 * 1024);
3739     qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
3740     fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
3741     object_unref(OBJECT(s->bioc));
3742 
3743     update_iteration_initial_status(s);
3744 
3745     /*
3746      * Prepare for tracking memory writes with UFFD-WP - populate
3747      * RAM pages before protecting.
3748      */
3749 #ifdef __linux__
3750     ram_write_tracking_prepare();
3751 #endif
3752 
3753     bql_lock();
3754     qemu_savevm_state_header(s->to_dst_file);
3755     ret = qemu_savevm_state_setup(s->to_dst_file, &local_err);
3756     bql_unlock();
3757 
3758     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3759                                MIGRATION_STATUS_ACTIVE);
3760 
3761     /*
3762      * Handle SETUP failures after waiting for virtio-net-failover
3763      * devices to unplug. This to preserve migration state transitions.
3764      */
3765     if (ret) {
3766         migrate_set_error(s, local_err);
3767         error_free(local_err);
3768         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3769                           MIGRATION_STATUS_FAILED);
3770         goto fail_setup;
3771     }
3772 
3773     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3774 
3775     trace_migration_thread_setup_complete();
3776 
3777     bql_lock();
3778 
3779     if (migration_stop_vm(s, RUN_STATE_PAUSED)) {
3780         goto fail;
3781     }
3782 
3783     if (qemu_savevm_state_complete_precopy_non_iterable(fb, false)) {
3784         goto fail;
3785     }
3786     /*
3787      * Since we are going to get non-iterable state data directly
3788      * from s->bioc->data, explicit flush is needed here.
3789      */
3790     qemu_fflush(fb);
3791 
3792     /* Now initialize UFFD context and start tracking RAM writes */
3793     if (ram_write_tracking_start()) {
3794         goto fail;
3795     }
3796     early_fail = false;
3797 
3798     /*
3799      * Start VM from BH handler to avoid write-fault lock here.
3800      * UFFD-WP protection for the whole RAM is already enabled so
3801      * calling VM state change notifiers from vm_start() would initiate
3802      * writes to virtio VQs memory which is in write-protected region.
3803      */
3804     migration_bh_schedule(bg_migration_vm_start_bh, s);
3805     bql_unlock();
3806 
3807     while (migration_is_active()) {
3808         MigIterateState iter_state = bg_migration_iteration_run(s);
3809         if (iter_state == MIG_ITERATE_SKIP) {
3810             continue;
3811         } else if (iter_state == MIG_ITERATE_BREAK) {
3812             break;
3813         }
3814 
3815         /*
3816          * Try to detect any kind of failures, and see whether we
3817          * should stop the migration now.
3818          */
3819         thr_error = migration_detect_error(s);
3820         if (thr_error == MIG_THR_ERR_FATAL) {
3821             /* Stop migration */
3822             break;
3823         }
3824 
3825         migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
3826     }
3827 
3828     trace_migration_thread_after_loop();
3829 
3830 fail:
3831     if (early_fail) {
3832         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3833                 MIGRATION_STATUS_FAILED);
3834         bql_unlock();
3835     }
3836 
3837 fail_setup:
3838     bg_migration_iteration_finish(s);
3839 
3840     qemu_fclose(fb);
3841     object_unref(OBJECT(s));
3842     rcu_unregister_thread();
3843 
3844     return NULL;
3845 }
3846 
3847 void migrate_fd_connect(MigrationState *s, Error *error_in)
3848 {
3849     Error *local_err = NULL;
3850     uint64_t rate_limit;
3851     bool resume = (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP);
3852     int ret;
3853 
3854     /*
3855      * If there's a previous error, free it and prepare for another one.
3856      * Meanwhile if migration completes successfully, there won't have an error
3857      * dumped when calling migrate_fd_cleanup().
3858      */
3859     migrate_error_free(s);
3860 
3861     s->expected_downtime = migrate_downtime_limit();
3862     if (error_in) {
3863         migrate_fd_error(s, error_in);
3864         if (resume) {
3865             /*
3866              * Don't do cleanup for resume if channel is invalid, but only dump
3867              * the error.  We wait for another channel connect from the user.
3868              * The error_report still gives HMP user a hint on what failed.
3869              * It's normally done in migrate_fd_cleanup(), but call it here
3870              * explicitly.
3871              */
3872             error_report_err(error_copy(s->error));
3873         } else {
3874             migrate_fd_cleanup(s);
3875         }
3876         return;
3877     }
3878 
3879     if (resume) {
3880         /* This is a resumed migration */
3881         rate_limit = migrate_max_postcopy_bandwidth();
3882     } else {
3883         /* This is a fresh new migration */
3884         rate_limit = migrate_max_bandwidth();
3885 
3886         /* Notify before starting migration thread */
3887         if (migration_call_notifiers(s, MIG_EVENT_PRECOPY_SETUP, &local_err)) {
3888             goto fail;
3889         }
3890     }
3891 
3892     migration_rate_set(rate_limit);
3893     qemu_file_set_blocking(s->to_dst_file, true);
3894 
3895     /*
3896      * Open the return path. For postcopy, it is used exclusively. For
3897      * precopy, only if user specified "return-path" capability would
3898      * QEMU uses the return path.
3899      */
3900     if (migrate_postcopy_ram() || migrate_return_path()) {
3901         if (open_return_path_on_source(s)) {
3902             error_setg(&local_err, "Unable to open return-path for postcopy");
3903             goto fail;
3904         }
3905     }
3906 
3907     /*
3908      * This needs to be done before resuming a postcopy.  Note: for newer
3909      * QEMUs we will delay the channel creation until postcopy_start(), to
3910      * avoid disorder of channel creations.
3911      */
3912     if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
3913         postcopy_preempt_setup(s);
3914     }
3915 
3916     if (resume) {
3917         /* Wakeup the main migration thread to do the recovery */
3918         migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER_SETUP,
3919                           MIGRATION_STATUS_POSTCOPY_RECOVER);
3920         qemu_sem_post(&s->postcopy_pause_sem);
3921         return;
3922     }
3923 
3924     if (migrate_mode_is_cpr(s)) {
3925         ret = migration_stop_vm(s, RUN_STATE_FINISH_MIGRATE);
3926         if (ret < 0) {
3927             error_setg(&local_err, "migration_stop_vm failed, error %d", -ret);
3928             goto fail;
3929         }
3930     }
3931 
3932     /*
3933      * Take a refcount to make sure the migration object won't get freed by
3934      * the main thread already in migration_shutdown().
3935      *
3936      * The refcount will be released at the end of the thread function.
3937      */
3938     object_ref(OBJECT(s));
3939 
3940     if (migrate_background_snapshot()) {
3941         qemu_thread_create(&s->thread, MIGRATION_THREAD_SNAPSHOT,
3942                 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
3943     } else {
3944         qemu_thread_create(&s->thread, MIGRATION_THREAD_SRC_MAIN,
3945                 migration_thread, s, QEMU_THREAD_JOINABLE);
3946     }
3947     s->migration_thread_running = true;
3948     return;
3949 
3950 fail:
3951     migrate_set_error(s, local_err);
3952     migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3953     error_report_err(local_err);
3954     migrate_fd_cleanup(s);
3955 }
3956 
3957 static void migration_class_init(ObjectClass *klass, void *data)
3958 {
3959     DeviceClass *dc = DEVICE_CLASS(klass);
3960 
3961     dc->user_creatable = false;
3962     device_class_set_props_n(dc, migration_properties,
3963                              migration_properties_count);
3964 }
3965 
3966 static void migration_instance_finalize(Object *obj)
3967 {
3968     MigrationState *ms = MIGRATION_OBJ(obj);
3969 
3970     qemu_mutex_destroy(&ms->error_mutex);
3971     qemu_mutex_destroy(&ms->qemu_file_lock);
3972     qemu_sem_destroy(&ms->wait_unplug_sem);
3973     qemu_sem_destroy(&ms->rate_limit_sem);
3974     qemu_sem_destroy(&ms->pause_sem);
3975     qemu_sem_destroy(&ms->postcopy_pause_sem);
3976     qemu_sem_destroy(&ms->rp_state.rp_sem);
3977     qemu_sem_destroy(&ms->rp_state.rp_pong_acks);
3978     qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
3979     error_free(ms->error);
3980 }
3981 
3982 static void migration_instance_init(Object *obj)
3983 {
3984     MigrationState *ms = MIGRATION_OBJ(obj);
3985 
3986     ms->state = MIGRATION_STATUS_NONE;
3987     ms->mbps = -1;
3988     ms->pages_per_second = -1;
3989     qemu_sem_init(&ms->pause_sem, 0);
3990     qemu_mutex_init(&ms->error_mutex);
3991 
3992     migrate_params_init(&ms->parameters);
3993 
3994     qemu_sem_init(&ms->postcopy_pause_sem, 0);
3995     qemu_sem_init(&ms->rp_state.rp_sem, 0);
3996     qemu_sem_init(&ms->rp_state.rp_pong_acks, 0);
3997     qemu_sem_init(&ms->rate_limit_sem, 0);
3998     qemu_sem_init(&ms->wait_unplug_sem, 0);
3999     qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
4000     qemu_mutex_init(&ms->qemu_file_lock);
4001 }
4002 
4003 /*
4004  * Return true if check pass, false otherwise. Error will be put
4005  * inside errp if provided.
4006  */
4007 static bool migration_object_check(MigrationState *ms, Error **errp)
4008 {
4009     /* Assuming all off */
4010     bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
4011 
4012     if (!migrate_params_check(&ms->parameters, errp)) {
4013         return false;
4014     }
4015 
4016     return migrate_caps_check(old_caps, ms->capabilities, errp);
4017 }
4018 
4019 static const TypeInfo migration_type = {
4020     .name = TYPE_MIGRATION,
4021     /*
4022      * NOTE: TYPE_MIGRATION is not really a device, as the object is
4023      * not created using qdev_new(), it is not attached to the qdev
4024      * device tree, and it is never realized.
4025      *
4026      * TODO: Make this TYPE_OBJECT once QOM provides something like
4027      * TYPE_DEVICE's "-global" properties.
4028      */
4029     .parent = TYPE_DEVICE,
4030     .class_init = migration_class_init,
4031     .class_size = sizeof(MigrationClass),
4032     .instance_size = sizeof(MigrationState),
4033     .instance_init = migration_instance_init,
4034     .instance_finalize = migration_instance_finalize,
4035 };
4036 
4037 static void register_migration_types(void)
4038 {
4039     type_register_static(&migration_type);
4040 }
4041 
4042 type_init(register_migration_types);
4043