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