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