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