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