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