xref: /openbmc/qemu/migration/migration.c (revision 047f2ca1cec9cdb226f4eac7e672f753089a42ee)
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 "socket.h"
24 #include "sysemu/runstate.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/cpu-throttle.h"
27 #include "rdma.h"
28 #include "ram.h"
29 #include "migration/global_state.h"
30 #include "migration/misc.h"
31 #include "migration.h"
32 #include "savevm.h"
33 #include "qemu-file.h"
34 #include "migration/vmstate.h"
35 #include "block/block.h"
36 #include "qapi/error.h"
37 #include "qapi/clone-visitor.h"
38 #include "qapi/qapi-visit-migration.h"
39 #include "qapi/qapi-visit-sockets.h"
40 #include "qapi/qapi-commands-migration.h"
41 #include "qapi/qapi-events-migration.h"
42 #include "qapi/qmp/qerror.h"
43 #include "qapi/qmp/qnull.h"
44 #include "qemu/rcu.h"
45 #include "block.h"
46 #include "postcopy-ram.h"
47 #include "qemu/thread.h"
48 #include "trace.h"
49 #include "exec/target_page.h"
50 #include "io/channel-buffer.h"
51 #include "io/channel-tls.h"
52 #include "migration/colo.h"
53 #include "hw/boards.h"
54 #include "hw/qdev-properties.h"
55 #include "hw/qdev-properties-system.h"
56 #include "monitor/monitor.h"
57 #include "net/announce.h"
58 #include "qemu/queue.h"
59 #include "multifd.h"
60 #include "qemu/yank.h"
61 #include "sysemu/cpus.h"
62 #include "yank_functions.h"
63 #include "sysemu/qtest.h"
64 
65 #define MAX_THROTTLE  (128 << 20)      /* Migration transfer speed throttling */
66 
67 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
68  * data. */
69 #define BUFFER_DELAY     100
70 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
71 
72 /* Time in milliseconds we are allowed to stop the source,
73  * for sending the last part */
74 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
75 
76 /* Maximum migrate downtime set to 2000 seconds */
77 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
78 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
79 
80 /* Default compression thread count */
81 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
82 /* Default decompression thread count, usually decompression is at
83  * least 4 times as fast as compression.*/
84 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
85 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
86 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
87 /* Define default autoconverge cpu throttle migration parameters */
88 #define DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD 50
89 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
90 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
91 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
92 
93 /* Migration XBZRLE default cache size */
94 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
95 
96 /* The delay time (in ms) between two COLO checkpoints */
97 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
98 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
99 #define DEFAULT_MIGRATE_MULTIFD_COMPRESSION MULTIFD_COMPRESSION_NONE
100 /* 0: means nocompress, 1: best speed, ... 9: best compress ratio */
101 #define DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL 1
102 /* 0: means nocompress, 1: best speed, ... 20: best compress ratio */
103 #define DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL 1
104 
105 /* Background transfer rate for postcopy, 0 means unlimited, note
106  * that page requests can still exceed this limit.
107  */
108 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
109 
110 /*
111  * Parameters for self_announce_delay giving a stream of RARP/ARP
112  * packets after migration.
113  */
114 #define DEFAULT_MIGRATE_ANNOUNCE_INITIAL  50
115 #define DEFAULT_MIGRATE_ANNOUNCE_MAX     550
116 #define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS    5
117 #define DEFAULT_MIGRATE_ANNOUNCE_STEP    100
118 
119 static NotifierList migration_state_notifiers =
120     NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
121 
122 /* Messages sent on the return path from destination to source */
123 enum mig_rp_message_type {
124     MIG_RP_MSG_INVALID = 0,  /* Must be 0 */
125     MIG_RP_MSG_SHUT,         /* sibling will not send any more RP messages */
126     MIG_RP_MSG_PONG,         /* Response to a PING; data (seq: be32 ) */
127 
128     MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
129     MIG_RP_MSG_REQ_PAGES,    /* data (start: be64, len: be32) */
130     MIG_RP_MSG_RECV_BITMAP,  /* send recved_bitmap back to source */
131     MIG_RP_MSG_RESUME_ACK,   /* tell source that we are ready to resume */
132 
133     MIG_RP_MSG_MAX
134 };
135 
136 /* Migration capabilities set */
137 struct MigrateCapsSet {
138     int size;                       /* Capability set size */
139     MigrationCapability caps[];     /* Variadic array of capabilities */
140 };
141 typedef struct MigrateCapsSet MigrateCapsSet;
142 
143 /* Define and initialize MigrateCapsSet */
144 #define INITIALIZE_MIGRATE_CAPS_SET(_name, ...)   \
145     MigrateCapsSet _name = {    \
146         .size = sizeof((int []) { __VA_ARGS__ }) / sizeof(int), \
147         .caps = { __VA_ARGS__ } \
148     }
149 
150 /* Background-snapshot compatibility check list */
151 static const
152 INITIALIZE_MIGRATE_CAPS_SET(check_caps_background_snapshot,
153     MIGRATION_CAPABILITY_POSTCOPY_RAM,
154     MIGRATION_CAPABILITY_DIRTY_BITMAPS,
155     MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME,
156     MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE,
157     MIGRATION_CAPABILITY_RETURN_PATH,
158     MIGRATION_CAPABILITY_MULTIFD,
159     MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER,
160     MIGRATION_CAPABILITY_AUTO_CONVERGE,
161     MIGRATION_CAPABILITY_RELEASE_RAM,
162     MIGRATION_CAPABILITY_RDMA_PIN_ALL,
163     MIGRATION_CAPABILITY_COMPRESS,
164     MIGRATION_CAPABILITY_XBZRLE,
165     MIGRATION_CAPABILITY_X_COLO,
166     MIGRATION_CAPABILITY_VALIDATE_UUID,
167     MIGRATION_CAPABILITY_ZERO_COPY_SEND);
168 
169 /* When we add fault tolerance, we could have several
170    migrations at once.  For now we don't need to add
171    dynamic creation of migration */
172 
173 static MigrationState *current_migration;
174 static MigrationIncomingState *current_incoming;
175 
176 static GSList *migration_blockers;
177 
178 static bool migration_object_check(MigrationState *ms, Error **errp);
179 static int migration_maybe_pause(MigrationState *s,
180                                  int *current_active_state,
181                                  int new_state);
182 static void migrate_fd_cancel(MigrationState *s);
183 
184 static bool migrate_allow_multi_channels = true;
185 
186 void migrate_protocol_allow_multi_channels(bool allow)
187 {
188     migrate_allow_multi_channels = allow;
189 }
190 
191 bool migrate_multi_channels_is_allowed(void)
192 {
193     return migrate_allow_multi_channels;
194 }
195 
196 static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
197 {
198     uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
199 
200     return (a > b) - (a < b);
201 }
202 
203 void migration_object_init(void)
204 {
205     /* This can only be called once. */
206     assert(!current_migration);
207     current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
208 
209     /*
210      * Init the migrate incoming object as well no matter whether
211      * we'll use it or not.
212      */
213     assert(!current_incoming);
214     current_incoming = g_new0(MigrationIncomingState, 1);
215     current_incoming->state = MIGRATION_STATUS_NONE;
216     current_incoming->postcopy_remote_fds =
217         g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
218     qemu_mutex_init(&current_incoming->rp_mutex);
219     qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
220     qemu_event_init(&current_incoming->main_thread_load_event, false);
221     qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
222     qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
223     qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
224     qemu_mutex_init(&current_incoming->page_request_mutex);
225     current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
226 
227     migration_object_check(current_migration, &error_fatal);
228 
229     blk_mig_init();
230     ram_mig_init();
231     dirty_bitmap_mig_init();
232 }
233 
234 void migration_cancel(const Error *error)
235 {
236     if (error) {
237         migrate_set_error(current_migration, error);
238     }
239     migrate_fd_cancel(current_migration);
240 }
241 
242 void migration_shutdown(void)
243 {
244     /*
245      * When the QEMU main thread exit, the COLO thread
246      * may wait a semaphore. So, we should wakeup the
247      * COLO thread before migration shutdown.
248      */
249     colo_shutdown();
250     /*
251      * Cancel the current migration - that will (eventually)
252      * stop the migration using this structure
253      */
254     migration_cancel(NULL);
255     object_unref(OBJECT(current_migration));
256 
257     /*
258      * Cancel outgoing migration of dirty bitmaps. It should
259      * at least unref used block nodes.
260      */
261     dirty_bitmap_mig_cancel_outgoing();
262 
263     /*
264      * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
265      * are non-critical data, and their loss never considered as
266      * something serious.
267      */
268     dirty_bitmap_mig_cancel_incoming();
269 }
270 
271 /* For outgoing */
272 MigrationState *migrate_get_current(void)
273 {
274     /* This can only be called after the object created. */
275     assert(current_migration);
276     return current_migration;
277 }
278 
279 MigrationIncomingState *migration_incoming_get_current(void)
280 {
281     assert(current_incoming);
282     return current_incoming;
283 }
284 
285 void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
286 {
287     if (mis->socket_address_list) {
288         qapi_free_SocketAddressList(mis->socket_address_list);
289         mis->socket_address_list = NULL;
290     }
291 
292     if (mis->transport_cleanup) {
293         mis->transport_cleanup(mis->transport_data);
294         mis->transport_data = mis->transport_cleanup = NULL;
295     }
296 }
297 
298 void migration_incoming_state_destroy(void)
299 {
300     struct MigrationIncomingState *mis = migration_incoming_get_current();
301 
302     if (mis->to_src_file) {
303         /* Tell source that we are done */
304         migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
305         qemu_fclose(mis->to_src_file);
306         mis->to_src_file = NULL;
307     }
308 
309     if (mis->from_src_file) {
310         migration_ioc_unregister_yank_from_file(mis->from_src_file);
311         qemu_fclose(mis->from_src_file);
312         mis->from_src_file = NULL;
313     }
314     if (mis->postcopy_remote_fds) {
315         g_array_free(mis->postcopy_remote_fds, TRUE);
316         mis->postcopy_remote_fds = NULL;
317     }
318 
319     migration_incoming_transport_cleanup(mis);
320     qemu_event_reset(&mis->main_thread_load_event);
321 
322     if (mis->page_requested) {
323         g_tree_destroy(mis->page_requested);
324         mis->page_requested = NULL;
325     }
326 
327     if (mis->postcopy_qemufile_dst) {
328         migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
329         qemu_fclose(mis->postcopy_qemufile_dst);
330         mis->postcopy_qemufile_dst = NULL;
331     }
332 
333     yank_unregister_instance(MIGRATION_YANK_INSTANCE);
334 }
335 
336 static void migrate_generate_event(int new_state)
337 {
338     if (migrate_use_events()) {
339         qapi_event_send_migration(new_state);
340     }
341 }
342 
343 static bool migrate_late_block_activate(void)
344 {
345     MigrationState *s;
346 
347     s = migrate_get_current();
348 
349     return s->enabled_capabilities[
350         MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
351 }
352 
353 /*
354  * Send a message on the return channel back to the source
355  * of the migration.
356  */
357 static int migrate_send_rp_message(MigrationIncomingState *mis,
358                                    enum mig_rp_message_type message_type,
359                                    uint16_t len, void *data)
360 {
361     int ret = 0;
362 
363     trace_migrate_send_rp_message((int)message_type, len);
364     QEMU_LOCK_GUARD(&mis->rp_mutex);
365 
366     /*
367      * It's possible that the file handle got lost due to network
368      * failures.
369      */
370     if (!mis->to_src_file) {
371         ret = -EIO;
372         return ret;
373     }
374 
375     qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
376     qemu_put_be16(mis->to_src_file, len);
377     qemu_put_buffer(mis->to_src_file, data, len);
378     qemu_fflush(mis->to_src_file);
379 
380     /* It's possible that qemu file got error during sending */
381     ret = qemu_file_get_error(mis->to_src_file);
382 
383     return ret;
384 }
385 
386 /* Request one page from the source VM at the given start address.
387  *   rb: the RAMBlock to request the page in
388  *   Start: Address offset within the RB
389  *   Len: Length in bytes required - must be a multiple of pagesize
390  */
391 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
392                                       RAMBlock *rb, ram_addr_t start)
393 {
394     uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
395     size_t msglen = 12; /* start + len */
396     size_t len = qemu_ram_pagesize(rb);
397     enum mig_rp_message_type msg_type;
398     const char *rbname;
399     int rbname_len;
400 
401     *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
402     *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
403 
404     /*
405      * We maintain the last ramblock that we requested for page.  Note that we
406      * don't need locking because this function will only be called within the
407      * postcopy ram fault thread.
408      */
409     if (rb != mis->last_rb) {
410         mis->last_rb = rb;
411 
412         rbname = qemu_ram_get_idstr(rb);
413         rbname_len = strlen(rbname);
414 
415         assert(rbname_len < 256);
416 
417         bufc[msglen++] = rbname_len;
418         memcpy(bufc + msglen, rbname, rbname_len);
419         msglen += rbname_len;
420         msg_type = MIG_RP_MSG_REQ_PAGES_ID;
421     } else {
422         msg_type = MIG_RP_MSG_REQ_PAGES;
423     }
424 
425     return migrate_send_rp_message(mis, msg_type, msglen, bufc);
426 }
427 
428 int migrate_send_rp_req_pages(MigrationIncomingState *mis,
429                               RAMBlock *rb, ram_addr_t start, uint64_t haddr)
430 {
431     void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
432     bool received = false;
433 
434     WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
435         received = ramblock_recv_bitmap_test_byte_offset(rb, start);
436         if (!received && !g_tree_lookup(mis->page_requested, aligned)) {
437             /*
438              * The page has not been received, and it's not yet in the page
439              * request list.  Queue it.  Set the value of element to 1, so that
440              * things like g_tree_lookup() will return TRUE (1) when found.
441              */
442             g_tree_insert(mis->page_requested, aligned, (gpointer)1);
443             mis->page_requested_count++;
444             trace_postcopy_page_req_add(aligned, mis->page_requested_count);
445         }
446     }
447 
448     /*
449      * If the page is there, skip sending the message.  We don't even need the
450      * lock because as long as the page arrived, it'll be there forever.
451      */
452     if (received) {
453         return 0;
454     }
455 
456     return migrate_send_rp_message_req_pages(mis, rb, start);
457 }
458 
459 static bool migration_colo_enabled;
460 bool migration_incoming_colo_enabled(void)
461 {
462     return migration_colo_enabled;
463 }
464 
465 void migration_incoming_disable_colo(void)
466 {
467     ram_block_discard_disable(false);
468     migration_colo_enabled = false;
469 }
470 
471 int migration_incoming_enable_colo(void)
472 {
473     if (ram_block_discard_disable(true)) {
474         error_report("COLO: cannot disable RAM discard");
475         return -EBUSY;
476     }
477     migration_colo_enabled = true;
478     return 0;
479 }
480 
481 void migrate_add_address(SocketAddress *address)
482 {
483     MigrationIncomingState *mis = migration_incoming_get_current();
484 
485     QAPI_LIST_PREPEND(mis->socket_address_list,
486                       QAPI_CLONE(SocketAddress, address));
487 }
488 
489 static void qemu_start_incoming_migration(const char *uri, Error **errp)
490 {
491     const char *p = NULL;
492 
493     migrate_protocol_allow_multi_channels(false); /* reset it anyway */
494     qapi_event_send_migration(MIGRATION_STATUS_SETUP);
495     if (strstart(uri, "tcp:", &p) ||
496         strstart(uri, "unix:", NULL) ||
497         strstart(uri, "vsock:", NULL)) {
498         migrate_protocol_allow_multi_channels(true);
499         socket_start_incoming_migration(p ? p : uri, errp);
500 #ifdef CONFIG_RDMA
501     } else if (strstart(uri, "rdma:", &p)) {
502         rdma_start_incoming_migration(p, errp);
503 #endif
504     } else if (strstart(uri, "exec:", &p)) {
505         exec_start_incoming_migration(p, errp);
506     } else if (strstart(uri, "fd:", &p)) {
507         fd_start_incoming_migration(p, errp);
508     } else {
509         error_setg(errp, "unknown migration protocol: %s", uri);
510     }
511 }
512 
513 static void process_incoming_migration_bh(void *opaque)
514 {
515     Error *local_err = NULL;
516     MigrationIncomingState *mis = opaque;
517 
518     /* If capability late_block_activate is set:
519      * Only fire up the block code now if we're going to restart the
520      * VM, else 'cont' will do it.
521      * This causes file locking to happen; so we don't want it to happen
522      * unless we really are starting the VM.
523      */
524     if (!migrate_late_block_activate() ||
525          (autostart && (!global_state_received() ||
526             global_state_get_runstate() == RUN_STATE_RUNNING))) {
527         /* Make sure all file formats throw away their mutable metadata.
528          * If we get an error here, just don't restart the VM yet. */
529         bdrv_activate_all(&local_err);
530         if (local_err) {
531             error_report_err(local_err);
532             local_err = NULL;
533             autostart = false;
534         }
535     }
536 
537     /*
538      * This must happen after all error conditions are dealt with and
539      * we're sure the VM is going to be running on this host.
540      */
541     qemu_announce_self(&mis->announce_timer, migrate_announce_params());
542 
543     if (multifd_load_cleanup(&local_err) != 0) {
544         error_report_err(local_err);
545         autostart = false;
546     }
547     /* If global state section was not received or we are in running
548        state, we need to obey autostart. Any other state is set with
549        runstate_set. */
550 
551     dirty_bitmap_mig_before_vm_start();
552 
553     if (!global_state_received() ||
554         global_state_get_runstate() == RUN_STATE_RUNNING) {
555         if (autostart) {
556             vm_start();
557         } else {
558             runstate_set(RUN_STATE_PAUSED);
559         }
560     } else if (migration_incoming_colo_enabled()) {
561         migration_incoming_disable_colo();
562         vm_start();
563     } else {
564         runstate_set(global_state_get_runstate());
565     }
566     /*
567      * This must happen after any state changes since as soon as an external
568      * observer sees this event they might start to prod at the VM assuming
569      * it's ready to use.
570      */
571     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
572                       MIGRATION_STATUS_COMPLETED);
573     qemu_bh_delete(mis->bh);
574     migration_incoming_state_destroy();
575 }
576 
577 static void coroutine_fn
578 process_incoming_migration_co(void *opaque)
579 {
580     MigrationIncomingState *mis = migration_incoming_get_current();
581     PostcopyState ps;
582     int ret;
583     Error *local_err = NULL;
584 
585     assert(mis->from_src_file);
586     mis->migration_incoming_co = qemu_coroutine_self();
587     mis->largest_page_size = qemu_ram_pagesize_largest();
588     postcopy_state_set(POSTCOPY_INCOMING_NONE);
589     migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
590                       MIGRATION_STATUS_ACTIVE);
591     ret = qemu_loadvm_state(mis->from_src_file);
592 
593     ps = postcopy_state_get();
594     trace_process_incoming_migration_co_end(ret, ps);
595     if (ps != POSTCOPY_INCOMING_NONE) {
596         if (ps == POSTCOPY_INCOMING_ADVISE) {
597             /*
598              * Where a migration had postcopy enabled (and thus went to advise)
599              * but managed to complete within the precopy period, we can use
600              * the normal exit.
601              */
602             postcopy_ram_incoming_cleanup(mis);
603         } else if (ret >= 0) {
604             /*
605              * Postcopy was started, cleanup should happen at the end of the
606              * postcopy thread.
607              */
608             trace_process_incoming_migration_co_postcopy_end_main();
609             return;
610         }
611         /* Else if something went wrong then just fall out of the normal exit */
612     }
613 
614     /* we get COLO info, and know if we are in COLO mode */
615     if (!ret && migration_incoming_colo_enabled()) {
616         /* Make sure all file formats throw away their mutable metadata */
617         bdrv_activate_all(&local_err);
618         if (local_err) {
619             error_report_err(local_err);
620             goto fail;
621         }
622 
623         qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
624              colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
625         mis->have_colo_incoming_thread = true;
626         qemu_coroutine_yield();
627 
628         qemu_mutex_unlock_iothread();
629         /* Wait checkpoint incoming thread exit before free resource */
630         qemu_thread_join(&mis->colo_incoming_thread);
631         qemu_mutex_lock_iothread();
632         /* We hold the global iothread lock, so it is safe here */
633         colo_release_ram_cache();
634     }
635 
636     if (ret < 0) {
637         error_report("load of migration failed: %s", strerror(-ret));
638         goto fail;
639     }
640     mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
641     qemu_bh_schedule(mis->bh);
642     mis->migration_incoming_co = NULL;
643     return;
644 fail:
645     local_err = NULL;
646     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
647                       MIGRATION_STATUS_FAILED);
648     qemu_fclose(mis->from_src_file);
649     if (multifd_load_cleanup(&local_err) != 0) {
650         error_report_err(local_err);
651     }
652     exit(EXIT_FAILURE);
653 }
654 
655 /**
656  * migration_incoming_setup: Setup incoming migration
657  * @f: file for main migration channel
658  * @errp: where to put errors
659  *
660  * Returns: %true on success, %false on error.
661  */
662 static bool migration_incoming_setup(QEMUFile *f, Error **errp)
663 {
664     MigrationIncomingState *mis = migration_incoming_get_current();
665 
666     if (multifd_load_setup(errp) != 0) {
667         return false;
668     }
669 
670     if (!mis->from_src_file) {
671         mis->from_src_file = f;
672     }
673     qemu_file_set_blocking(f, false);
674     return true;
675 }
676 
677 void migration_incoming_process(void)
678 {
679     Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
680     qemu_coroutine_enter(co);
681 }
682 
683 /* Returns true if recovered from a paused migration, otherwise false */
684 static bool postcopy_try_recover(void)
685 {
686     MigrationIncomingState *mis = migration_incoming_get_current();
687 
688     if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
689         /* Resumed from a paused postcopy migration */
690 
691         /* This should be set already in migration_incoming_setup() */
692         assert(mis->from_src_file);
693         /* Postcopy has standalone thread to do vm load */
694         qemu_file_set_blocking(mis->from_src_file, true);
695 
696         /* Re-configure the return path */
697         mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
698 
699         migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
700                           MIGRATION_STATUS_POSTCOPY_RECOVER);
701 
702         /*
703          * Here, we only wake up the main loading thread (while the
704          * rest threads will still be waiting), so that we can receive
705          * commands from source now, and answer it if needed. The
706          * rest threads will be woken up afterwards until we are sure
707          * that source is ready to reply to page requests.
708          */
709         qemu_sem_post(&mis->postcopy_pause_sem_dst);
710         return true;
711     }
712 
713     return false;
714 }
715 
716 void migration_fd_process_incoming(QEMUFile *f, Error **errp)
717 {
718     if (!migration_incoming_setup(f, errp)) {
719         return;
720     }
721     if (postcopy_try_recover()) {
722         return;
723     }
724     migration_incoming_process();
725 }
726 
727 static bool migration_needs_multiple_sockets(void)
728 {
729     return migrate_use_multifd() || migrate_postcopy_preempt();
730 }
731 
732 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
733 {
734     MigrationIncomingState *mis = migration_incoming_get_current();
735     Error *local_err = NULL;
736     bool start_migration;
737     QEMUFile *f;
738 
739     if (!mis->from_src_file) {
740         /* The first connection (multifd may have multiple) */
741         f = qemu_file_new_input(ioc);
742 
743         if (!migration_incoming_setup(f, errp)) {
744             return;
745         }
746 
747         /*
748          * Common migration only needs one channel, so we can start
749          * right now.  Some features need more than one channel, we wait.
750          */
751         start_migration = !migration_needs_multiple_sockets();
752     } else {
753         /* Multiple connections */
754         assert(migration_needs_multiple_sockets());
755         if (migrate_use_multifd()) {
756             start_migration = multifd_recv_new_channel(ioc, &local_err);
757         } else {
758             assert(migrate_postcopy_preempt());
759             f = qemu_file_new_input(ioc);
760             start_migration = postcopy_preempt_new_channel(mis, f);
761         }
762         if (local_err) {
763             error_propagate(errp, local_err);
764             return;
765         }
766     }
767 
768     if (start_migration) {
769         /* If it's a recovery, we're done */
770         if (postcopy_try_recover()) {
771             return;
772         }
773         migration_incoming_process();
774     }
775 }
776 
777 /**
778  * @migration_has_all_channels: We have received all channels that we need
779  *
780  * Returns true when we have got connections to all the channels that
781  * we need for migration.
782  */
783 bool migration_has_all_channels(void)
784 {
785     MigrationIncomingState *mis = migration_incoming_get_current();
786 
787     if (!mis->from_src_file) {
788         return false;
789     }
790 
791     if (migrate_use_multifd()) {
792         return multifd_recv_all_channels_created();
793     }
794 
795     if (migrate_postcopy_preempt()) {
796         return mis->postcopy_qemufile_dst != NULL;
797     }
798 
799     return true;
800 }
801 
802 /*
803  * Send a 'SHUT' message on the return channel with the given value
804  * to indicate that we've finished with the RP.  Non-0 value indicates
805  * error.
806  */
807 void migrate_send_rp_shut(MigrationIncomingState *mis,
808                           uint32_t value)
809 {
810     uint32_t buf;
811 
812     buf = cpu_to_be32(value);
813     migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
814 }
815 
816 /*
817  * Send a 'PONG' message on the return channel with the given value
818  * (normally in response to a 'PING')
819  */
820 void migrate_send_rp_pong(MigrationIncomingState *mis,
821                           uint32_t value)
822 {
823     uint32_t buf;
824 
825     buf = cpu_to_be32(value);
826     migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
827 }
828 
829 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
830                                  char *block_name)
831 {
832     char buf[512];
833     int len;
834     int64_t res;
835 
836     /*
837      * First, we send the header part. It contains only the len of
838      * idstr, and the idstr itself.
839      */
840     len = strlen(block_name);
841     buf[0] = len;
842     memcpy(buf + 1, block_name, len);
843 
844     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
845         error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
846                      __func__);
847         return;
848     }
849 
850     migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
851 
852     /*
853      * Next, we dump the received bitmap to the stream.
854      *
855      * TODO: currently we are safe since we are the only one that is
856      * using the to_src_file handle (fault thread is still paused),
857      * and it's ok even not taking the mutex. However the best way is
858      * to take the lock before sending the message header, and release
859      * the lock after sending the bitmap.
860      */
861     qemu_mutex_lock(&mis->rp_mutex);
862     res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
863     qemu_mutex_unlock(&mis->rp_mutex);
864 
865     trace_migrate_send_rp_recv_bitmap(block_name, res);
866 }
867 
868 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
869 {
870     uint32_t buf;
871 
872     buf = cpu_to_be32(value);
873     migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
874 }
875 
876 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
877 {
878     MigrationCapabilityStatusList *head = NULL, **tail = &head;
879     MigrationCapabilityStatus *caps;
880     MigrationState *s = migrate_get_current();
881     int i;
882 
883     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
884 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
885         if (i == MIGRATION_CAPABILITY_BLOCK) {
886             continue;
887         }
888 #endif
889         caps = g_malloc0(sizeof(*caps));
890         caps->capability = i;
891         caps->state = s->enabled_capabilities[i];
892         QAPI_LIST_APPEND(tail, caps);
893     }
894 
895     return head;
896 }
897 
898 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
899 {
900     MigrationParameters *params;
901     MigrationState *s = migrate_get_current();
902 
903     /* TODO use QAPI_CLONE() instead of duplicating it inline */
904     params = g_malloc0(sizeof(*params));
905     params->has_compress_level = true;
906     params->compress_level = s->parameters.compress_level;
907     params->has_compress_threads = true;
908     params->compress_threads = s->parameters.compress_threads;
909     params->has_compress_wait_thread = true;
910     params->compress_wait_thread = s->parameters.compress_wait_thread;
911     params->has_decompress_threads = true;
912     params->decompress_threads = s->parameters.decompress_threads;
913     params->has_throttle_trigger_threshold = true;
914     params->throttle_trigger_threshold = s->parameters.throttle_trigger_threshold;
915     params->has_cpu_throttle_initial = true;
916     params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
917     params->has_cpu_throttle_increment = true;
918     params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
919     params->has_cpu_throttle_tailslow = true;
920     params->cpu_throttle_tailslow = s->parameters.cpu_throttle_tailslow;
921     params->tls_creds = g_strdup(s->parameters.tls_creds);
922     params->tls_hostname = g_strdup(s->parameters.tls_hostname);
923     params->tls_authz = g_strdup(s->parameters.tls_authz ?
924                                  s->parameters.tls_authz : "");
925     params->has_max_bandwidth = true;
926     params->max_bandwidth = s->parameters.max_bandwidth;
927     params->has_downtime_limit = true;
928     params->downtime_limit = s->parameters.downtime_limit;
929     params->has_x_checkpoint_delay = true;
930     params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
931     params->has_block_incremental = true;
932     params->block_incremental = s->parameters.block_incremental;
933     params->has_multifd_channels = true;
934     params->multifd_channels = s->parameters.multifd_channels;
935     params->has_multifd_compression = true;
936     params->multifd_compression = s->parameters.multifd_compression;
937     params->has_multifd_zlib_level = true;
938     params->multifd_zlib_level = s->parameters.multifd_zlib_level;
939     params->has_multifd_zstd_level = true;
940     params->multifd_zstd_level = s->parameters.multifd_zstd_level;
941     params->has_xbzrle_cache_size = true;
942     params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
943     params->has_max_postcopy_bandwidth = true;
944     params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
945     params->has_max_cpu_throttle = true;
946     params->max_cpu_throttle = s->parameters.max_cpu_throttle;
947     params->has_announce_initial = true;
948     params->announce_initial = s->parameters.announce_initial;
949     params->has_announce_max = true;
950     params->announce_max = s->parameters.announce_max;
951     params->has_announce_rounds = true;
952     params->announce_rounds = s->parameters.announce_rounds;
953     params->has_announce_step = true;
954     params->announce_step = s->parameters.announce_step;
955 
956     if (s->parameters.has_block_bitmap_mapping) {
957         params->has_block_bitmap_mapping = true;
958         params->block_bitmap_mapping =
959             QAPI_CLONE(BitmapMigrationNodeAliasList,
960                        s->parameters.block_bitmap_mapping);
961     }
962 
963     return params;
964 }
965 
966 AnnounceParameters *migrate_announce_params(void)
967 {
968     static AnnounceParameters ap;
969 
970     MigrationState *s = migrate_get_current();
971 
972     ap.initial = s->parameters.announce_initial;
973     ap.max = s->parameters.announce_max;
974     ap.rounds = s->parameters.announce_rounds;
975     ap.step = s->parameters.announce_step;
976 
977     return &ap;
978 }
979 
980 /*
981  * Return true if we're already in the middle of a migration
982  * (i.e. any of the active or setup states)
983  */
984 bool migration_is_setup_or_active(int state)
985 {
986     switch (state) {
987     case MIGRATION_STATUS_ACTIVE:
988     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
989     case MIGRATION_STATUS_POSTCOPY_PAUSED:
990     case MIGRATION_STATUS_POSTCOPY_RECOVER:
991     case MIGRATION_STATUS_SETUP:
992     case MIGRATION_STATUS_PRE_SWITCHOVER:
993     case MIGRATION_STATUS_DEVICE:
994     case MIGRATION_STATUS_WAIT_UNPLUG:
995     case MIGRATION_STATUS_COLO:
996         return true;
997 
998     default:
999         return false;
1000 
1001     }
1002 }
1003 
1004 bool migration_is_running(int state)
1005 {
1006     switch (state) {
1007     case MIGRATION_STATUS_ACTIVE:
1008     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1009     case MIGRATION_STATUS_POSTCOPY_PAUSED:
1010     case MIGRATION_STATUS_POSTCOPY_RECOVER:
1011     case MIGRATION_STATUS_SETUP:
1012     case MIGRATION_STATUS_PRE_SWITCHOVER:
1013     case MIGRATION_STATUS_DEVICE:
1014     case MIGRATION_STATUS_WAIT_UNPLUG:
1015     case MIGRATION_STATUS_CANCELLING:
1016         return true;
1017 
1018     default:
1019         return false;
1020 
1021     }
1022 }
1023 
1024 static void populate_time_info(MigrationInfo *info, MigrationState *s)
1025 {
1026     info->has_status = true;
1027     info->has_setup_time = true;
1028     info->setup_time = s->setup_time;
1029     if (s->state == MIGRATION_STATUS_COMPLETED) {
1030         info->has_total_time = true;
1031         info->total_time = s->total_time;
1032         info->has_downtime = true;
1033         info->downtime = s->downtime;
1034     } else {
1035         info->has_total_time = true;
1036         info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
1037                            s->start_time;
1038         info->has_expected_downtime = true;
1039         info->expected_downtime = s->expected_downtime;
1040     }
1041 }
1042 
1043 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
1044 {
1045     size_t page_size = qemu_target_page_size();
1046 
1047     info->ram = g_malloc0(sizeof(*info->ram));
1048     info->ram->transferred = ram_counters.transferred;
1049     info->ram->total = ram_bytes_total();
1050     info->ram->duplicate = ram_counters.duplicate;
1051     /* legacy value.  It is not used anymore */
1052     info->ram->skipped = 0;
1053     info->ram->normal = ram_counters.normal;
1054     info->ram->normal_bytes = ram_counters.normal * page_size;
1055     info->ram->mbps = s->mbps;
1056     info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
1057     info->ram->dirty_sync_missed_zero_copy =
1058             ram_counters.dirty_sync_missed_zero_copy;
1059     info->ram->postcopy_requests = ram_counters.postcopy_requests;
1060     info->ram->page_size = page_size;
1061     info->ram->multifd_bytes = ram_counters.multifd_bytes;
1062     info->ram->pages_per_second = s->pages_per_second;
1063     info->ram->precopy_bytes = ram_counters.precopy_bytes;
1064     info->ram->downtime_bytes = ram_counters.downtime_bytes;
1065     info->ram->postcopy_bytes = ram_counters.postcopy_bytes;
1066 
1067     if (migrate_use_xbzrle()) {
1068         info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
1069         info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
1070         info->xbzrle_cache->bytes = xbzrle_counters.bytes;
1071         info->xbzrle_cache->pages = xbzrle_counters.pages;
1072         info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
1073         info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
1074         info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
1075         info->xbzrle_cache->overflow = xbzrle_counters.overflow;
1076     }
1077 
1078     if (migrate_use_compression()) {
1079         info->compression = g_malloc0(sizeof(*info->compression));
1080         info->compression->pages = compression_counters.pages;
1081         info->compression->busy = compression_counters.busy;
1082         info->compression->busy_rate = compression_counters.busy_rate;
1083         info->compression->compressed_size =
1084                                     compression_counters.compressed_size;
1085         info->compression->compression_rate =
1086                                     compression_counters.compression_rate;
1087     }
1088 
1089     if (cpu_throttle_active()) {
1090         info->has_cpu_throttle_percentage = true;
1091         info->cpu_throttle_percentage = cpu_throttle_get_percentage();
1092     }
1093 
1094     if (s->state != MIGRATION_STATUS_COMPLETED) {
1095         info->ram->remaining = ram_bytes_remaining();
1096         info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
1097     }
1098 }
1099 
1100 static void populate_disk_info(MigrationInfo *info)
1101 {
1102     if (blk_mig_active()) {
1103         info->disk = g_malloc0(sizeof(*info->disk));
1104         info->disk->transferred = blk_mig_bytes_transferred();
1105         info->disk->remaining = blk_mig_bytes_remaining();
1106         info->disk->total = blk_mig_bytes_total();
1107     }
1108 }
1109 
1110 static void fill_source_migration_info(MigrationInfo *info)
1111 {
1112     MigrationState *s = migrate_get_current();
1113     int state = qatomic_read(&s->state);
1114     GSList *cur_blocker = migration_blockers;
1115 
1116     info->blocked_reasons = NULL;
1117 
1118     /*
1119      * There are two types of reasons a migration might be blocked;
1120      * a) devices marked in VMState as non-migratable, and
1121      * b) Explicit migration blockers
1122      * We need to add both of them here.
1123      */
1124     qemu_savevm_non_migratable_list(&info->blocked_reasons);
1125 
1126     while (cur_blocker) {
1127         QAPI_LIST_PREPEND(info->blocked_reasons,
1128                           g_strdup(error_get_pretty(cur_blocker->data)));
1129         cur_blocker = g_slist_next(cur_blocker);
1130     }
1131     info->has_blocked_reasons = info->blocked_reasons != NULL;
1132 
1133     switch (state) {
1134     case MIGRATION_STATUS_NONE:
1135         /* no migration has happened ever */
1136         /* do not overwrite destination migration status */
1137         return;
1138     case MIGRATION_STATUS_SETUP:
1139         info->has_status = true;
1140         info->has_total_time = false;
1141         break;
1142     case MIGRATION_STATUS_ACTIVE:
1143     case MIGRATION_STATUS_CANCELLING:
1144     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1145     case MIGRATION_STATUS_PRE_SWITCHOVER:
1146     case MIGRATION_STATUS_DEVICE:
1147     case MIGRATION_STATUS_POSTCOPY_PAUSED:
1148     case MIGRATION_STATUS_POSTCOPY_RECOVER:
1149         /* TODO add some postcopy stats */
1150         populate_time_info(info, s);
1151         populate_ram_info(info, s);
1152         populate_disk_info(info);
1153         populate_vfio_info(info);
1154         break;
1155     case MIGRATION_STATUS_COLO:
1156         info->has_status = true;
1157         /* TODO: display COLO specific information (checkpoint info etc.) */
1158         break;
1159     case MIGRATION_STATUS_COMPLETED:
1160         populate_time_info(info, s);
1161         populate_ram_info(info, s);
1162         populate_vfio_info(info);
1163         break;
1164     case MIGRATION_STATUS_FAILED:
1165         info->has_status = true;
1166         if (s->error) {
1167             info->error_desc = g_strdup(error_get_pretty(s->error));
1168         }
1169         break;
1170     case MIGRATION_STATUS_CANCELLED:
1171         info->has_status = true;
1172         break;
1173     case MIGRATION_STATUS_WAIT_UNPLUG:
1174         info->has_status = true;
1175         break;
1176     }
1177     info->status = state;
1178 }
1179 
1180 typedef enum WriteTrackingSupport {
1181     WT_SUPPORT_UNKNOWN = 0,
1182     WT_SUPPORT_ABSENT,
1183     WT_SUPPORT_AVAILABLE,
1184     WT_SUPPORT_COMPATIBLE
1185 } WriteTrackingSupport;
1186 
1187 static
1188 WriteTrackingSupport migrate_query_write_tracking(void)
1189 {
1190     /* Check if kernel supports required UFFD features */
1191     if (!ram_write_tracking_available()) {
1192         return WT_SUPPORT_ABSENT;
1193     }
1194     /*
1195      * Check if current memory configuration is
1196      * compatible with required UFFD features.
1197      */
1198     if (!ram_write_tracking_compatible()) {
1199         return WT_SUPPORT_AVAILABLE;
1200     }
1201 
1202     return WT_SUPPORT_COMPATIBLE;
1203 }
1204 
1205 /**
1206  * @migration_caps_check - check capability validity
1207  *
1208  * @cap_list: old capability list, array of bool
1209  * @params: new capabilities to be applied soon
1210  * @errp: set *errp if the check failed, with reason
1211  *
1212  * Returns true if check passed, otherwise false.
1213  */
1214 static bool migrate_caps_check(bool *cap_list,
1215                                MigrationCapabilityStatusList *params,
1216                                Error **errp)
1217 {
1218     MigrationCapabilityStatusList *cap;
1219     bool old_postcopy_cap;
1220     MigrationIncomingState *mis = migration_incoming_get_current();
1221 
1222     old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1223 
1224     for (cap = params; cap; cap = cap->next) {
1225         cap_list[cap->value->capability] = cap->value->state;
1226     }
1227 
1228 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
1229     if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
1230         error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
1231                    "block migration");
1232         error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
1233         return false;
1234     }
1235 #endif
1236 
1237 #ifndef CONFIG_REPLICATION
1238     if (cap_list[MIGRATION_CAPABILITY_X_COLO]) {
1239         error_setg(errp, "QEMU compiled without replication module"
1240                    " can't enable COLO");
1241         error_append_hint(errp, "Please enable replication before COLO.\n");
1242         return false;
1243     }
1244 #endif
1245 
1246     if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1247         /* This check is reasonably expensive, so only when it's being
1248          * set the first time, also it's only the destination that needs
1249          * special support.
1250          */
1251         if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
1252             !postcopy_ram_supported_by_host(mis)) {
1253             /* postcopy_ram_supported_by_host will have emitted a more
1254              * detailed message
1255              */
1256             error_setg(errp, "Postcopy is not supported");
1257             return false;
1258         }
1259 
1260         if (cap_list[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) {
1261             error_setg(errp, "Postcopy is not compatible with ignore-shared");
1262             return false;
1263         }
1264     }
1265 
1266     if (cap_list[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT]) {
1267         WriteTrackingSupport wt_support;
1268         int idx;
1269         /*
1270          * Check if 'background-snapshot' capability is supported by
1271          * host kernel and compatible with guest memory configuration.
1272          */
1273         wt_support = migrate_query_write_tracking();
1274         if (wt_support < WT_SUPPORT_AVAILABLE) {
1275             error_setg(errp, "Background-snapshot is not supported by host kernel");
1276             return false;
1277         }
1278         if (wt_support < WT_SUPPORT_COMPATIBLE) {
1279             error_setg(errp, "Background-snapshot is not compatible "
1280                     "with guest memory configuration");
1281             return false;
1282         }
1283 
1284         /*
1285          * Check if there are any migration capabilities
1286          * incompatible with 'background-snapshot'.
1287          */
1288         for (idx = 0; idx < check_caps_background_snapshot.size; idx++) {
1289             int incomp_cap = check_caps_background_snapshot.caps[idx];
1290             if (cap_list[incomp_cap]) {
1291                 error_setg(errp,
1292                         "Background-snapshot is not compatible with %s",
1293                         MigrationCapability_str(incomp_cap));
1294                 return false;
1295             }
1296         }
1297     }
1298 
1299 #ifdef CONFIG_LINUX
1300     if (cap_list[MIGRATION_CAPABILITY_ZERO_COPY_SEND] &&
1301         (!cap_list[MIGRATION_CAPABILITY_MULTIFD] ||
1302          cap_list[MIGRATION_CAPABILITY_COMPRESS] ||
1303          cap_list[MIGRATION_CAPABILITY_XBZRLE] ||
1304          migrate_multifd_compression() ||
1305          migrate_use_tls())) {
1306         error_setg(errp,
1307                    "Zero copy only available for non-compressed non-TLS multifd migration");
1308         return false;
1309     }
1310 #else
1311     if (cap_list[MIGRATION_CAPABILITY_ZERO_COPY_SEND]) {
1312         error_setg(errp,
1313                    "Zero copy currently only available on Linux");
1314         return false;
1315     }
1316 #endif
1317 
1318 
1319     /* incoming side only */
1320     if (runstate_check(RUN_STATE_INMIGRATE) &&
1321         !migrate_multi_channels_is_allowed() &&
1322         cap_list[MIGRATION_CAPABILITY_MULTIFD]) {
1323         error_setg(errp, "multifd is not supported by current protocol");
1324         return false;
1325     }
1326 
1327     if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_PREEMPT]) {
1328         if (!cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1329             error_setg(errp, "Postcopy preempt requires postcopy-ram");
1330             return false;
1331         }
1332 
1333         /*
1334          * Preempt mode requires urgent pages to be sent in separate
1335          * channel, OTOH compression logic will disorder all pages into
1336          * different compression channels, which is not compatible with the
1337          * preempt assumptions on channel assignments.
1338          */
1339         if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
1340             error_setg(errp, "Postcopy preempt not compatible with compress");
1341             return false;
1342         }
1343     }
1344 
1345     if (cap_list[MIGRATION_CAPABILITY_MULTIFD]) {
1346         if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
1347             error_setg(errp, "Multifd is not compatible with compress");
1348             return false;
1349         }
1350     }
1351 
1352     return true;
1353 }
1354 
1355 static void fill_destination_migration_info(MigrationInfo *info)
1356 {
1357     MigrationIncomingState *mis = migration_incoming_get_current();
1358 
1359     if (mis->socket_address_list) {
1360         info->has_socket_address = true;
1361         info->socket_address =
1362             QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1363     }
1364 
1365     switch (mis->state) {
1366     case MIGRATION_STATUS_NONE:
1367         return;
1368     case MIGRATION_STATUS_SETUP:
1369     case MIGRATION_STATUS_CANCELLING:
1370     case MIGRATION_STATUS_CANCELLED:
1371     case MIGRATION_STATUS_ACTIVE:
1372     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1373     case MIGRATION_STATUS_POSTCOPY_PAUSED:
1374     case MIGRATION_STATUS_POSTCOPY_RECOVER:
1375     case MIGRATION_STATUS_FAILED:
1376     case MIGRATION_STATUS_COLO:
1377         info->has_status = true;
1378         break;
1379     case MIGRATION_STATUS_COMPLETED:
1380         info->has_status = true;
1381         fill_destination_postcopy_migration_info(info);
1382         break;
1383     }
1384     info->status = mis->state;
1385 }
1386 
1387 MigrationInfo *qmp_query_migrate(Error **errp)
1388 {
1389     MigrationInfo *info = g_malloc0(sizeof(*info));
1390 
1391     fill_destination_migration_info(info);
1392     fill_source_migration_info(info);
1393 
1394     return info;
1395 }
1396 
1397 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
1398                                   Error **errp)
1399 {
1400     MigrationState *s = migrate_get_current();
1401     MigrationCapabilityStatusList *cap;
1402     bool cap_list[MIGRATION_CAPABILITY__MAX];
1403 
1404     if (migration_is_running(s->state)) {
1405         error_setg(errp, QERR_MIGRATION_ACTIVE);
1406         return;
1407     }
1408 
1409     memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
1410     if (!migrate_caps_check(cap_list, params, errp)) {
1411         return;
1412     }
1413 
1414     for (cap = params; cap; cap = cap->next) {
1415         s->enabled_capabilities[cap->value->capability] = cap->value->state;
1416     }
1417 }
1418 
1419 /*
1420  * Check whether the parameters are valid. Error will be put into errp
1421  * (if provided). Return true if valid, otherwise false.
1422  */
1423 static bool migrate_params_check(MigrationParameters *params, Error **errp)
1424 {
1425     if (params->has_compress_level &&
1426         (params->compress_level > 9)) {
1427         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
1428                    "a value between 0 and 9");
1429         return false;
1430     }
1431 
1432     if (params->has_compress_threads && (params->compress_threads < 1)) {
1433         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1434                    "compress_threads",
1435                    "a value between 1 and 255");
1436         return false;
1437     }
1438 
1439     if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1440         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1441                    "decompress_threads",
1442                    "a value between 1 and 255");
1443         return false;
1444     }
1445 
1446     if (params->has_throttle_trigger_threshold &&
1447         (params->throttle_trigger_threshold < 1 ||
1448          params->throttle_trigger_threshold > 100)) {
1449         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1450                    "throttle_trigger_threshold",
1451                    "an integer in the range of 1 to 100");
1452         return false;
1453     }
1454 
1455     if (params->has_cpu_throttle_initial &&
1456         (params->cpu_throttle_initial < 1 ||
1457          params->cpu_throttle_initial > 99)) {
1458         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1459                    "cpu_throttle_initial",
1460                    "an integer in the range of 1 to 99");
1461         return false;
1462     }
1463 
1464     if (params->has_cpu_throttle_increment &&
1465         (params->cpu_throttle_increment < 1 ||
1466          params->cpu_throttle_increment > 99)) {
1467         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1468                    "cpu_throttle_increment",
1469                    "an integer in the range of 1 to 99");
1470         return false;
1471     }
1472 
1473     if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1474         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1475                    "max_bandwidth",
1476                    "an integer in the range of 0 to "stringify(SIZE_MAX)
1477                    " bytes/second");
1478         return false;
1479     }
1480 
1481     if (params->has_downtime_limit &&
1482         (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1483         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1484                    "downtime_limit",
1485                    "an integer in the range of 0 to "
1486                     stringify(MAX_MIGRATE_DOWNTIME)" ms");
1487         return false;
1488     }
1489 
1490     /* x_checkpoint_delay is now always positive */
1491 
1492     if (params->has_multifd_channels && (params->multifd_channels < 1)) {
1493         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1494                    "multifd_channels",
1495                    "a value between 1 and 255");
1496         return false;
1497     }
1498 
1499     if (params->has_multifd_zlib_level &&
1500         (params->multifd_zlib_level > 9)) {
1501         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zlib_level",
1502                    "a value between 0 and 9");
1503         return false;
1504     }
1505 
1506     if (params->has_multifd_zstd_level &&
1507         (params->multifd_zstd_level > 20)) {
1508         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zstd_level",
1509                    "a value between 0 and 20");
1510         return false;
1511     }
1512 
1513     if (params->has_xbzrle_cache_size &&
1514         (params->xbzrle_cache_size < qemu_target_page_size() ||
1515          !is_power_of_2(params->xbzrle_cache_size))) {
1516         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1517                    "xbzrle_cache_size",
1518                    "a power of two no less than the target page size");
1519         return false;
1520     }
1521 
1522     if (params->has_max_cpu_throttle &&
1523         (params->max_cpu_throttle < params->cpu_throttle_initial ||
1524          params->max_cpu_throttle > 99)) {
1525         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1526                    "max_cpu_throttle",
1527                    "an integer in the range of cpu_throttle_initial to 99");
1528         return false;
1529     }
1530 
1531     if (params->has_announce_initial &&
1532         params->announce_initial > 100000) {
1533         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1534                    "announce_initial",
1535                    "a value between 0 and 100000");
1536         return false;
1537     }
1538     if (params->has_announce_max &&
1539         params->announce_max > 100000) {
1540         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1541                    "announce_max",
1542                    "a value between 0 and 100000");
1543        return false;
1544     }
1545     if (params->has_announce_rounds &&
1546         params->announce_rounds > 1000) {
1547         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1548                    "announce_rounds",
1549                    "a value between 0 and 1000");
1550        return false;
1551     }
1552     if (params->has_announce_step &&
1553         (params->announce_step < 1 ||
1554         params->announce_step > 10000)) {
1555         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1556                    "announce_step",
1557                    "a value between 0 and 10000");
1558        return false;
1559     }
1560 
1561     if (params->has_block_bitmap_mapping &&
1562         !check_dirty_bitmap_mig_alias_map(params->block_bitmap_mapping, errp)) {
1563         error_prepend(errp, "Invalid mapping given for block-bitmap-mapping: ");
1564         return false;
1565     }
1566 
1567 #ifdef CONFIG_LINUX
1568     if (migrate_use_zero_copy_send() &&
1569         ((params->has_multifd_compression && params->multifd_compression) ||
1570          (params->tls_creds && *params->tls_creds))) {
1571         error_setg(errp,
1572                    "Zero copy only available for non-compressed non-TLS multifd migration");
1573         return false;
1574     }
1575 #endif
1576 
1577     return true;
1578 }
1579 
1580 static void migrate_params_test_apply(MigrateSetParameters *params,
1581                                       MigrationParameters *dest)
1582 {
1583     *dest = migrate_get_current()->parameters;
1584 
1585     /* TODO use QAPI_CLONE() instead of duplicating it inline */
1586 
1587     if (params->has_compress_level) {
1588         dest->compress_level = params->compress_level;
1589     }
1590 
1591     if (params->has_compress_threads) {
1592         dest->compress_threads = params->compress_threads;
1593     }
1594 
1595     if (params->has_compress_wait_thread) {
1596         dest->compress_wait_thread = params->compress_wait_thread;
1597     }
1598 
1599     if (params->has_decompress_threads) {
1600         dest->decompress_threads = params->decompress_threads;
1601     }
1602 
1603     if (params->has_throttle_trigger_threshold) {
1604         dest->throttle_trigger_threshold = params->throttle_trigger_threshold;
1605     }
1606 
1607     if (params->has_cpu_throttle_initial) {
1608         dest->cpu_throttle_initial = params->cpu_throttle_initial;
1609     }
1610 
1611     if (params->has_cpu_throttle_increment) {
1612         dest->cpu_throttle_increment = params->cpu_throttle_increment;
1613     }
1614 
1615     if (params->has_cpu_throttle_tailslow) {
1616         dest->cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1617     }
1618 
1619     if (params->tls_creds) {
1620         assert(params->tls_creds->type == QTYPE_QSTRING);
1621         dest->tls_creds = params->tls_creds->u.s;
1622     }
1623 
1624     if (params->tls_hostname) {
1625         assert(params->tls_hostname->type == QTYPE_QSTRING);
1626         dest->tls_hostname = params->tls_hostname->u.s;
1627     }
1628 
1629     if (params->has_max_bandwidth) {
1630         dest->max_bandwidth = params->max_bandwidth;
1631     }
1632 
1633     if (params->has_downtime_limit) {
1634         dest->downtime_limit = params->downtime_limit;
1635     }
1636 
1637     if (params->has_x_checkpoint_delay) {
1638         dest->x_checkpoint_delay = params->x_checkpoint_delay;
1639     }
1640 
1641     if (params->has_block_incremental) {
1642         dest->block_incremental = params->block_incremental;
1643     }
1644     if (params->has_multifd_channels) {
1645         dest->multifd_channels = params->multifd_channels;
1646     }
1647     if (params->has_multifd_compression) {
1648         dest->multifd_compression = params->multifd_compression;
1649     }
1650     if (params->has_xbzrle_cache_size) {
1651         dest->xbzrle_cache_size = params->xbzrle_cache_size;
1652     }
1653     if (params->has_max_postcopy_bandwidth) {
1654         dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1655     }
1656     if (params->has_max_cpu_throttle) {
1657         dest->max_cpu_throttle = params->max_cpu_throttle;
1658     }
1659     if (params->has_announce_initial) {
1660         dest->announce_initial = params->announce_initial;
1661     }
1662     if (params->has_announce_max) {
1663         dest->announce_max = params->announce_max;
1664     }
1665     if (params->has_announce_rounds) {
1666         dest->announce_rounds = params->announce_rounds;
1667     }
1668     if (params->has_announce_step) {
1669         dest->announce_step = params->announce_step;
1670     }
1671 
1672     if (params->has_block_bitmap_mapping) {
1673         dest->has_block_bitmap_mapping = true;
1674         dest->block_bitmap_mapping = params->block_bitmap_mapping;
1675     }
1676 }
1677 
1678 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1679 {
1680     MigrationState *s = migrate_get_current();
1681 
1682     /* TODO use QAPI_CLONE() instead of duplicating it inline */
1683 
1684     if (params->has_compress_level) {
1685         s->parameters.compress_level = params->compress_level;
1686     }
1687 
1688     if (params->has_compress_threads) {
1689         s->parameters.compress_threads = params->compress_threads;
1690     }
1691 
1692     if (params->has_compress_wait_thread) {
1693         s->parameters.compress_wait_thread = params->compress_wait_thread;
1694     }
1695 
1696     if (params->has_decompress_threads) {
1697         s->parameters.decompress_threads = params->decompress_threads;
1698     }
1699 
1700     if (params->has_throttle_trigger_threshold) {
1701         s->parameters.throttle_trigger_threshold = params->throttle_trigger_threshold;
1702     }
1703 
1704     if (params->has_cpu_throttle_initial) {
1705         s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1706     }
1707 
1708     if (params->has_cpu_throttle_increment) {
1709         s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1710     }
1711 
1712     if (params->has_cpu_throttle_tailslow) {
1713         s->parameters.cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1714     }
1715 
1716     if (params->tls_creds) {
1717         g_free(s->parameters.tls_creds);
1718         assert(params->tls_creds->type == QTYPE_QSTRING);
1719         s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1720     }
1721 
1722     if (params->tls_hostname) {
1723         g_free(s->parameters.tls_hostname);
1724         assert(params->tls_hostname->type == QTYPE_QSTRING);
1725         s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1726     }
1727 
1728     if (params->tls_authz) {
1729         g_free(s->parameters.tls_authz);
1730         assert(params->tls_authz->type == QTYPE_QSTRING);
1731         s->parameters.tls_authz = g_strdup(params->tls_authz->u.s);
1732     }
1733 
1734     if (params->has_max_bandwidth) {
1735         s->parameters.max_bandwidth = params->max_bandwidth;
1736         if (s->to_dst_file && !migration_in_postcopy()) {
1737             qemu_file_set_rate_limit(s->to_dst_file,
1738                                 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1739         }
1740     }
1741 
1742     if (params->has_downtime_limit) {
1743         s->parameters.downtime_limit = params->downtime_limit;
1744     }
1745 
1746     if (params->has_x_checkpoint_delay) {
1747         s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1748         if (migration_in_colo_state()) {
1749             colo_checkpoint_notify(s);
1750         }
1751     }
1752 
1753     if (params->has_block_incremental) {
1754         s->parameters.block_incremental = params->block_incremental;
1755     }
1756     if (params->has_multifd_channels) {
1757         s->parameters.multifd_channels = params->multifd_channels;
1758     }
1759     if (params->has_multifd_compression) {
1760         s->parameters.multifd_compression = params->multifd_compression;
1761     }
1762     if (params->has_xbzrle_cache_size) {
1763         s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1764         xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1765     }
1766     if (params->has_max_postcopy_bandwidth) {
1767         s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1768         if (s->to_dst_file && migration_in_postcopy()) {
1769             qemu_file_set_rate_limit(s->to_dst_file,
1770                     s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO);
1771         }
1772     }
1773     if (params->has_max_cpu_throttle) {
1774         s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1775     }
1776     if (params->has_announce_initial) {
1777         s->parameters.announce_initial = params->announce_initial;
1778     }
1779     if (params->has_announce_max) {
1780         s->parameters.announce_max = params->announce_max;
1781     }
1782     if (params->has_announce_rounds) {
1783         s->parameters.announce_rounds = params->announce_rounds;
1784     }
1785     if (params->has_announce_step) {
1786         s->parameters.announce_step = params->announce_step;
1787     }
1788 
1789     if (params->has_block_bitmap_mapping) {
1790         qapi_free_BitmapMigrationNodeAliasList(
1791             s->parameters.block_bitmap_mapping);
1792 
1793         s->parameters.has_block_bitmap_mapping = true;
1794         s->parameters.block_bitmap_mapping =
1795             QAPI_CLONE(BitmapMigrationNodeAliasList,
1796                        params->block_bitmap_mapping);
1797     }
1798 }
1799 
1800 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1801 {
1802     MigrationParameters tmp;
1803 
1804     /* TODO Rewrite "" to null instead */
1805     if (params->tls_creds
1806         && params->tls_creds->type == QTYPE_QNULL) {
1807         qobject_unref(params->tls_creds->u.n);
1808         params->tls_creds->type = QTYPE_QSTRING;
1809         params->tls_creds->u.s = strdup("");
1810     }
1811     /* TODO Rewrite "" to null instead */
1812     if (params->tls_hostname
1813         && params->tls_hostname->type == QTYPE_QNULL) {
1814         qobject_unref(params->tls_hostname->u.n);
1815         params->tls_hostname->type = QTYPE_QSTRING;
1816         params->tls_hostname->u.s = strdup("");
1817     }
1818 
1819     migrate_params_test_apply(params, &tmp);
1820 
1821     if (!migrate_params_check(&tmp, errp)) {
1822         /* Invalid parameter */
1823         return;
1824     }
1825 
1826     migrate_params_apply(params, errp);
1827 }
1828 
1829 
1830 void qmp_migrate_start_postcopy(Error **errp)
1831 {
1832     MigrationState *s = migrate_get_current();
1833 
1834     if (!migrate_postcopy()) {
1835         error_setg(errp, "Enable postcopy with migrate_set_capability before"
1836                          " the start of migration");
1837         return;
1838     }
1839 
1840     if (s->state == MIGRATION_STATUS_NONE) {
1841         error_setg(errp, "Postcopy must be started after migration has been"
1842                          " started");
1843         return;
1844     }
1845     /*
1846      * we don't error if migration has finished since that would be racy
1847      * with issuing this command.
1848      */
1849     qatomic_set(&s->start_postcopy, true);
1850 }
1851 
1852 /* shared migration helpers */
1853 
1854 void migrate_set_state(int *state, int old_state, int new_state)
1855 {
1856     assert(new_state < MIGRATION_STATUS__MAX);
1857     if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
1858         trace_migrate_set_state(MigrationStatus_str(new_state));
1859         migrate_generate_event(new_state);
1860     }
1861 }
1862 
1863 static MigrationCapabilityStatus *migrate_cap_add(MigrationCapability index,
1864                                                   bool state)
1865 {
1866     MigrationCapabilityStatus *cap;
1867 
1868     cap = g_new0(MigrationCapabilityStatus, 1);
1869     cap->capability = index;
1870     cap->state = state;
1871 
1872     return cap;
1873 }
1874 
1875 void migrate_set_block_enabled(bool value, Error **errp)
1876 {
1877     MigrationCapabilityStatusList *cap = NULL;
1878 
1879     QAPI_LIST_PREPEND(cap, migrate_cap_add(MIGRATION_CAPABILITY_BLOCK, value));
1880     qmp_migrate_set_capabilities(cap, errp);
1881     qapi_free_MigrationCapabilityStatusList(cap);
1882 }
1883 
1884 static void migrate_set_block_incremental(MigrationState *s, bool value)
1885 {
1886     s->parameters.block_incremental = value;
1887 }
1888 
1889 static void block_cleanup_parameters(MigrationState *s)
1890 {
1891     if (s->must_remove_block_options) {
1892         /* setting to false can never fail */
1893         migrate_set_block_enabled(false, &error_abort);
1894         migrate_set_block_incremental(s, false);
1895         s->must_remove_block_options = false;
1896     }
1897 }
1898 
1899 static void migrate_fd_cleanup(MigrationState *s)
1900 {
1901     qemu_bh_delete(s->cleanup_bh);
1902     s->cleanup_bh = NULL;
1903 
1904     g_free(s->hostname);
1905     s->hostname = NULL;
1906 
1907     qemu_savevm_state_cleanup();
1908 
1909     if (s->to_dst_file) {
1910         QEMUFile *tmp;
1911 
1912         trace_migrate_fd_cleanup();
1913         qemu_mutex_unlock_iothread();
1914         if (s->migration_thread_running) {
1915             qemu_thread_join(&s->thread);
1916             s->migration_thread_running = false;
1917         }
1918         qemu_mutex_lock_iothread();
1919 
1920         multifd_save_cleanup();
1921         qemu_mutex_lock(&s->qemu_file_lock);
1922         tmp = s->to_dst_file;
1923         s->to_dst_file = NULL;
1924         qemu_mutex_unlock(&s->qemu_file_lock);
1925         /*
1926          * Close the file handle without the lock to make sure the
1927          * critical section won't block for long.
1928          */
1929         migration_ioc_unregister_yank_from_file(tmp);
1930         qemu_fclose(tmp);
1931     }
1932 
1933     if (s->postcopy_qemufile_src) {
1934         migration_ioc_unregister_yank_from_file(s->postcopy_qemufile_src);
1935         qemu_fclose(s->postcopy_qemufile_src);
1936         s->postcopy_qemufile_src = NULL;
1937     }
1938 
1939     assert(!migration_is_active(s));
1940 
1941     if (s->state == MIGRATION_STATUS_CANCELLING) {
1942         migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1943                           MIGRATION_STATUS_CANCELLED);
1944     }
1945 
1946     if (s->error) {
1947         /* It is used on info migrate.  We can't free it */
1948         error_report_err(error_copy(s->error));
1949     }
1950     notifier_list_notify(&migration_state_notifiers, s);
1951     block_cleanup_parameters(s);
1952     yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1953 }
1954 
1955 static void migrate_fd_cleanup_schedule(MigrationState *s)
1956 {
1957     /*
1958      * Ref the state for bh, because it may be called when
1959      * there're already no other refs
1960      */
1961     object_ref(OBJECT(s));
1962     qemu_bh_schedule(s->cleanup_bh);
1963 }
1964 
1965 static void migrate_fd_cleanup_bh(void *opaque)
1966 {
1967     MigrationState *s = opaque;
1968     migrate_fd_cleanup(s);
1969     object_unref(OBJECT(s));
1970 }
1971 
1972 void migrate_set_error(MigrationState *s, const Error *error)
1973 {
1974     QEMU_LOCK_GUARD(&s->error_mutex);
1975     if (!s->error) {
1976         s->error = error_copy(error);
1977     }
1978 }
1979 
1980 static void migrate_error_free(MigrationState *s)
1981 {
1982     QEMU_LOCK_GUARD(&s->error_mutex);
1983     if (s->error) {
1984         error_free(s->error);
1985         s->error = NULL;
1986     }
1987 }
1988 
1989 void migrate_fd_error(MigrationState *s, const Error *error)
1990 {
1991     trace_migrate_fd_error(error_get_pretty(error));
1992     assert(s->to_dst_file == NULL);
1993     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1994                       MIGRATION_STATUS_FAILED);
1995     migrate_set_error(s, error);
1996 }
1997 
1998 static void migrate_fd_cancel(MigrationState *s)
1999 {
2000     int old_state ;
2001     QEMUFile *f = migrate_get_current()->to_dst_file;
2002     trace_migrate_fd_cancel();
2003 
2004     WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
2005         if (s->rp_state.from_dst_file) {
2006             /* shutdown the rp socket, so causing the rp thread to shutdown */
2007             qemu_file_shutdown(s->rp_state.from_dst_file);
2008         }
2009     }
2010 
2011     do {
2012         old_state = s->state;
2013         if (!migration_is_running(old_state)) {
2014             break;
2015         }
2016         /* If the migration is paused, kick it out of the pause */
2017         if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
2018             qemu_sem_post(&s->pause_sem);
2019         }
2020         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
2021     } while (s->state != MIGRATION_STATUS_CANCELLING);
2022 
2023     /*
2024      * If we're unlucky the migration code might be stuck somewhere in a
2025      * send/write while the network has failed and is waiting to timeout;
2026      * if we've got shutdown(2) available then we can force it to quit.
2027      * The outgoing qemu file gets closed in migrate_fd_cleanup that is
2028      * called in a bh, so there is no race against this cancel.
2029      */
2030     if (s->state == MIGRATION_STATUS_CANCELLING && f) {
2031         qemu_file_shutdown(f);
2032     }
2033     if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
2034         Error *local_err = NULL;
2035 
2036         bdrv_activate_all(&local_err);
2037         if (local_err) {
2038             error_report_err(local_err);
2039         } else {
2040             s->block_inactive = false;
2041         }
2042     }
2043 }
2044 
2045 void add_migration_state_change_notifier(Notifier *notify)
2046 {
2047     notifier_list_add(&migration_state_notifiers, notify);
2048 }
2049 
2050 void remove_migration_state_change_notifier(Notifier *notify)
2051 {
2052     notifier_remove(notify);
2053 }
2054 
2055 bool migration_in_setup(MigrationState *s)
2056 {
2057     return s->state == MIGRATION_STATUS_SETUP;
2058 }
2059 
2060 bool migration_has_finished(MigrationState *s)
2061 {
2062     return s->state == MIGRATION_STATUS_COMPLETED;
2063 }
2064 
2065 bool migration_has_failed(MigrationState *s)
2066 {
2067     return (s->state == MIGRATION_STATUS_CANCELLED ||
2068             s->state == MIGRATION_STATUS_FAILED);
2069 }
2070 
2071 bool migration_in_postcopy(void)
2072 {
2073     MigrationState *s = migrate_get_current();
2074 
2075     switch (s->state) {
2076     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
2077     case MIGRATION_STATUS_POSTCOPY_PAUSED:
2078     case MIGRATION_STATUS_POSTCOPY_RECOVER:
2079         return true;
2080     default:
2081         return false;
2082     }
2083 }
2084 
2085 bool migration_in_postcopy_after_devices(MigrationState *s)
2086 {
2087     return migration_in_postcopy() && s->postcopy_after_devices;
2088 }
2089 
2090 bool migration_in_incoming_postcopy(void)
2091 {
2092     PostcopyState ps = postcopy_state_get();
2093 
2094     return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
2095 }
2096 
2097 bool migration_in_bg_snapshot(void)
2098 {
2099     MigrationState *s = migrate_get_current();
2100 
2101     return migrate_background_snapshot() &&
2102             migration_is_setup_or_active(s->state);
2103 }
2104 
2105 bool migration_is_idle(void)
2106 {
2107     MigrationState *s = current_migration;
2108 
2109     if (!s) {
2110         return true;
2111     }
2112 
2113     switch (s->state) {
2114     case MIGRATION_STATUS_NONE:
2115     case MIGRATION_STATUS_CANCELLED:
2116     case MIGRATION_STATUS_COMPLETED:
2117     case MIGRATION_STATUS_FAILED:
2118         return true;
2119     case MIGRATION_STATUS_SETUP:
2120     case MIGRATION_STATUS_CANCELLING:
2121     case MIGRATION_STATUS_ACTIVE:
2122     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
2123     case MIGRATION_STATUS_COLO:
2124     case MIGRATION_STATUS_PRE_SWITCHOVER:
2125     case MIGRATION_STATUS_DEVICE:
2126     case MIGRATION_STATUS_WAIT_UNPLUG:
2127         return false;
2128     case MIGRATION_STATUS__MAX:
2129         g_assert_not_reached();
2130     }
2131 
2132     return false;
2133 }
2134 
2135 bool migration_is_active(MigrationState *s)
2136 {
2137     return (s->state == MIGRATION_STATUS_ACTIVE ||
2138             s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2139 }
2140 
2141 void migrate_init(MigrationState *s)
2142 {
2143     /*
2144      * Reinitialise all migration state, except
2145      * parameters/capabilities that the user set, and
2146      * locks.
2147      */
2148     s->cleanup_bh = 0;
2149     s->vm_start_bh = 0;
2150     s->to_dst_file = NULL;
2151     s->state = MIGRATION_STATUS_NONE;
2152     s->rp_state.from_dst_file = NULL;
2153     s->rp_state.error = false;
2154     s->mbps = 0.0;
2155     s->pages_per_second = 0.0;
2156     s->downtime = 0;
2157     s->expected_downtime = 0;
2158     s->setup_time = 0;
2159     s->start_postcopy = false;
2160     s->postcopy_after_devices = false;
2161     s->migration_thread_running = false;
2162     error_free(s->error);
2163     s->error = NULL;
2164     s->hostname = NULL;
2165 
2166     migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
2167 
2168     s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2169     s->total_time = 0;
2170     s->vm_was_running = false;
2171     s->iteration_initial_bytes = 0;
2172     s->threshold_size = 0;
2173 }
2174 
2175 int migrate_add_blocker_internal(Error *reason, Error **errp)
2176 {
2177     /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
2178     if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) {
2179         error_propagate_prepend(errp, error_copy(reason),
2180                                 "disallowing migration blocker "
2181                                 "(migration/snapshot in progress) for: ");
2182         return -EBUSY;
2183     }
2184 
2185     migration_blockers = g_slist_prepend(migration_blockers, reason);
2186     return 0;
2187 }
2188 
2189 int migrate_add_blocker(Error *reason, Error **errp)
2190 {
2191     if (only_migratable) {
2192         error_propagate_prepend(errp, error_copy(reason),
2193                                 "disallowing migration blocker "
2194                                 "(--only-migratable) for: ");
2195         return -EACCES;
2196     }
2197 
2198     return migrate_add_blocker_internal(reason, errp);
2199 }
2200 
2201 void migrate_del_blocker(Error *reason)
2202 {
2203     migration_blockers = g_slist_remove(migration_blockers, reason);
2204 }
2205 
2206 void qmp_migrate_incoming(const char *uri, Error **errp)
2207 {
2208     Error *local_err = NULL;
2209     static bool once = true;
2210 
2211     if (!once) {
2212         error_setg(errp, "The incoming migration has already been started");
2213         return;
2214     }
2215     if (!runstate_check(RUN_STATE_INMIGRATE)) {
2216         error_setg(errp, "'-incoming' was not specified on the command line");
2217         return;
2218     }
2219 
2220     if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2221         return;
2222     }
2223 
2224     qemu_start_incoming_migration(uri, &local_err);
2225 
2226     if (local_err) {
2227         yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2228         error_propagate(errp, local_err);
2229         return;
2230     }
2231 
2232     once = false;
2233 }
2234 
2235 void qmp_migrate_recover(const char *uri, Error **errp)
2236 {
2237     MigrationIncomingState *mis = migration_incoming_get_current();
2238 
2239     /*
2240      * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
2241      * callers (no one should ignore a recover failure); if there is, it's a
2242      * programming error.
2243      */
2244     assert(errp);
2245 
2246     if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2247         error_setg(errp, "Migrate recover can only be run "
2248                    "when postcopy is paused.");
2249         return;
2250     }
2251 
2252     /* If there's an existing transport, release it */
2253     migration_incoming_transport_cleanup(mis);
2254 
2255     /*
2256      * Note that this call will never start a real migration; it will
2257      * only re-setup the migration stream and poke existing migration
2258      * to continue using that newly established channel.
2259      */
2260     qemu_start_incoming_migration(uri, errp);
2261 }
2262 
2263 void qmp_migrate_pause(Error **errp)
2264 {
2265     MigrationState *ms = migrate_get_current();
2266     MigrationIncomingState *mis = migration_incoming_get_current();
2267     int ret;
2268 
2269     if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2270         /* Source side, during postcopy */
2271         qemu_mutex_lock(&ms->qemu_file_lock);
2272         ret = qemu_file_shutdown(ms->to_dst_file);
2273         qemu_mutex_unlock(&ms->qemu_file_lock);
2274         if (ret) {
2275             error_setg(errp, "Failed to pause source migration");
2276         }
2277         return;
2278     }
2279 
2280     if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2281         ret = qemu_file_shutdown(mis->from_src_file);
2282         if (ret) {
2283             error_setg(errp, "Failed to pause destination migration");
2284         }
2285         return;
2286     }
2287 
2288     error_setg(errp, "migrate-pause is currently only supported "
2289                "during postcopy-active state");
2290 }
2291 
2292 bool migration_is_blocked(Error **errp)
2293 {
2294     if (qemu_savevm_state_blocked(errp)) {
2295         return true;
2296     }
2297 
2298     if (migration_blockers) {
2299         error_propagate(errp, error_copy(migration_blockers->data));
2300         return true;
2301     }
2302 
2303     return false;
2304 }
2305 
2306 /* Returns true if continue to migrate, or false if error detected */
2307 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
2308                             bool resume, Error **errp)
2309 {
2310     Error *local_err = NULL;
2311 
2312     if (resume) {
2313         if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2314             error_setg(errp, "Cannot resume if there is no "
2315                        "paused migration");
2316             return false;
2317         }
2318 
2319         /*
2320          * Postcopy recovery won't work well with release-ram
2321          * capability since release-ram will drop the page buffer as
2322          * long as the page is put into the send buffer.  So if there
2323          * is a network failure happened, any page buffers that have
2324          * not yet reached the destination VM but have already been
2325          * sent from the source VM will be lost forever.  Let's refuse
2326          * the client from resuming such a postcopy migration.
2327          * Luckily release-ram was designed to only be used when src
2328          * and destination VMs are on the same host, so it should be
2329          * fine.
2330          */
2331         if (migrate_release_ram()) {
2332             error_setg(errp, "Postcopy recovery cannot work "
2333                        "when release-ram capability is set");
2334             return false;
2335         }
2336 
2337         /* This is a resume, skip init status */
2338         return true;
2339     }
2340 
2341     if (migration_is_running(s->state)) {
2342         error_setg(errp, QERR_MIGRATION_ACTIVE);
2343         return false;
2344     }
2345 
2346     if (runstate_check(RUN_STATE_INMIGRATE)) {
2347         error_setg(errp, "Guest is waiting for an incoming migration");
2348         return false;
2349     }
2350 
2351     if (runstate_check(RUN_STATE_POSTMIGRATE)) {
2352         error_setg(errp, "Can't migrate the vm that was paused due to "
2353                    "previous migration");
2354         return false;
2355     }
2356 
2357     if (migration_is_blocked(errp)) {
2358         return false;
2359     }
2360 
2361     if (blk || blk_inc) {
2362         if (migrate_colo_enabled()) {
2363             error_setg(errp, "No disk migration is required in COLO mode");
2364             return false;
2365         }
2366         if (migrate_use_block() || migrate_use_block_incremental()) {
2367             error_setg(errp, "Command options are incompatible with "
2368                        "current migration capabilities");
2369             return false;
2370         }
2371         migrate_set_block_enabled(true, &local_err);
2372         if (local_err) {
2373             error_propagate(errp, local_err);
2374             return false;
2375         }
2376         s->must_remove_block_options = true;
2377     }
2378 
2379     if (blk_inc) {
2380         migrate_set_block_incremental(s, true);
2381     }
2382 
2383     migrate_init(s);
2384     /*
2385      * set ram_counters compression_counters memory to zero for a
2386      * new migration
2387      */
2388     memset(&ram_counters, 0, sizeof(ram_counters));
2389     memset(&compression_counters, 0, sizeof(compression_counters));
2390 
2391     return true;
2392 }
2393 
2394 void qmp_migrate(const char *uri, bool has_blk, bool blk,
2395                  bool has_inc, bool inc, bool has_detach, bool detach,
2396                  bool has_resume, bool resume, Error **errp)
2397 {
2398     Error *local_err = NULL;
2399     MigrationState *s = migrate_get_current();
2400     const char *p = NULL;
2401 
2402     if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
2403                          has_resume && resume, errp)) {
2404         /* Error detected, put into errp */
2405         return;
2406     }
2407 
2408     if (!(has_resume && resume)) {
2409         if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2410             return;
2411         }
2412     }
2413 
2414     migrate_protocol_allow_multi_channels(false);
2415     if (strstart(uri, "tcp:", &p) ||
2416         strstart(uri, "unix:", NULL) ||
2417         strstart(uri, "vsock:", NULL)) {
2418         migrate_protocol_allow_multi_channels(true);
2419         socket_start_outgoing_migration(s, p ? p : uri, &local_err);
2420 #ifdef CONFIG_RDMA
2421     } else if (strstart(uri, "rdma:", &p)) {
2422         rdma_start_outgoing_migration(s, p, &local_err);
2423 #endif
2424     } else if (strstart(uri, "exec:", &p)) {
2425         exec_start_outgoing_migration(s, p, &local_err);
2426     } else if (strstart(uri, "fd:", &p)) {
2427         fd_start_outgoing_migration(s, p, &local_err);
2428     } else {
2429         if (!(has_resume && resume)) {
2430             yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2431         }
2432         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
2433                    "a valid migration protocol");
2434         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2435                           MIGRATION_STATUS_FAILED);
2436         block_cleanup_parameters(s);
2437         return;
2438     }
2439 
2440     if (local_err) {
2441         if (!(has_resume && resume)) {
2442             yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2443         }
2444         migrate_fd_error(s, local_err);
2445         error_propagate(errp, local_err);
2446         return;
2447     }
2448 }
2449 
2450 void qmp_migrate_cancel(Error **errp)
2451 {
2452     migration_cancel(NULL);
2453 }
2454 
2455 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2456 {
2457     MigrationState *s = migrate_get_current();
2458     if (s->state != state) {
2459         error_setg(errp,  "Migration not in expected state: %s",
2460                    MigrationStatus_str(s->state));
2461         return;
2462     }
2463     qemu_sem_post(&s->pause_sem);
2464 }
2465 
2466 bool migrate_release_ram(void)
2467 {
2468     MigrationState *s;
2469 
2470     s = migrate_get_current();
2471 
2472     return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2473 }
2474 
2475 bool migrate_postcopy_ram(void)
2476 {
2477     MigrationState *s;
2478 
2479     s = migrate_get_current();
2480 
2481     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
2482 }
2483 
2484 bool migrate_postcopy(void)
2485 {
2486     return migrate_postcopy_ram() || migrate_dirty_bitmaps();
2487 }
2488 
2489 bool migrate_auto_converge(void)
2490 {
2491     MigrationState *s;
2492 
2493     s = migrate_get_current();
2494 
2495     return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2496 }
2497 
2498 bool migrate_zero_blocks(void)
2499 {
2500     MigrationState *s;
2501 
2502     s = migrate_get_current();
2503 
2504     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2505 }
2506 
2507 bool migrate_postcopy_blocktime(void)
2508 {
2509     MigrationState *s;
2510 
2511     s = migrate_get_current();
2512 
2513     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2514 }
2515 
2516 bool migrate_use_compression(void)
2517 {
2518     MigrationState *s;
2519 
2520     s = migrate_get_current();
2521 
2522     return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
2523 }
2524 
2525 int migrate_compress_level(void)
2526 {
2527     MigrationState *s;
2528 
2529     s = migrate_get_current();
2530 
2531     return s->parameters.compress_level;
2532 }
2533 
2534 int migrate_compress_threads(void)
2535 {
2536     MigrationState *s;
2537 
2538     s = migrate_get_current();
2539 
2540     return s->parameters.compress_threads;
2541 }
2542 
2543 int migrate_compress_wait_thread(void)
2544 {
2545     MigrationState *s;
2546 
2547     s = migrate_get_current();
2548 
2549     return s->parameters.compress_wait_thread;
2550 }
2551 
2552 int migrate_decompress_threads(void)
2553 {
2554     MigrationState *s;
2555 
2556     s = migrate_get_current();
2557 
2558     return s->parameters.decompress_threads;
2559 }
2560 
2561 bool migrate_dirty_bitmaps(void)
2562 {
2563     MigrationState *s;
2564 
2565     s = migrate_get_current();
2566 
2567     return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2568 }
2569 
2570 bool migrate_ignore_shared(void)
2571 {
2572     MigrationState *s;
2573 
2574     s = migrate_get_current();
2575 
2576     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2577 }
2578 
2579 bool migrate_validate_uuid(void)
2580 {
2581     MigrationState *s;
2582 
2583     s = migrate_get_current();
2584 
2585     return s->enabled_capabilities[MIGRATION_CAPABILITY_VALIDATE_UUID];
2586 }
2587 
2588 bool migrate_use_events(void)
2589 {
2590     MigrationState *s;
2591 
2592     s = migrate_get_current();
2593 
2594     return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2595 }
2596 
2597 bool migrate_use_multifd(void)
2598 {
2599     MigrationState *s;
2600 
2601     s = migrate_get_current();
2602 
2603     return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
2604 }
2605 
2606 bool migrate_pause_before_switchover(void)
2607 {
2608     MigrationState *s;
2609 
2610     s = migrate_get_current();
2611 
2612     return s->enabled_capabilities[
2613         MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2614 }
2615 
2616 int migrate_multifd_channels(void)
2617 {
2618     MigrationState *s;
2619 
2620     s = migrate_get_current();
2621 
2622     return s->parameters.multifd_channels;
2623 }
2624 
2625 MultiFDCompression migrate_multifd_compression(void)
2626 {
2627     MigrationState *s;
2628 
2629     s = migrate_get_current();
2630 
2631     assert(s->parameters.multifd_compression < MULTIFD_COMPRESSION__MAX);
2632     return s->parameters.multifd_compression;
2633 }
2634 
2635 int migrate_multifd_zlib_level(void)
2636 {
2637     MigrationState *s;
2638 
2639     s = migrate_get_current();
2640 
2641     return s->parameters.multifd_zlib_level;
2642 }
2643 
2644 int migrate_multifd_zstd_level(void)
2645 {
2646     MigrationState *s;
2647 
2648     s = migrate_get_current();
2649 
2650     return s->parameters.multifd_zstd_level;
2651 }
2652 
2653 #ifdef CONFIG_LINUX
2654 bool migrate_use_zero_copy_send(void)
2655 {
2656     MigrationState *s;
2657 
2658     s = migrate_get_current();
2659 
2660     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_COPY_SEND];
2661 }
2662 #endif
2663 
2664 int migrate_use_tls(void)
2665 {
2666     MigrationState *s;
2667 
2668     s = migrate_get_current();
2669 
2670     return s->parameters.tls_creds && *s->parameters.tls_creds;
2671 }
2672 
2673 int migrate_use_xbzrle(void)
2674 {
2675     MigrationState *s;
2676 
2677     s = migrate_get_current();
2678 
2679     return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2680 }
2681 
2682 uint64_t migrate_xbzrle_cache_size(void)
2683 {
2684     MigrationState *s;
2685 
2686     s = migrate_get_current();
2687 
2688     return s->parameters.xbzrle_cache_size;
2689 }
2690 
2691 static int64_t migrate_max_postcopy_bandwidth(void)
2692 {
2693     MigrationState *s;
2694 
2695     s = migrate_get_current();
2696 
2697     return s->parameters.max_postcopy_bandwidth;
2698 }
2699 
2700 bool migrate_use_block(void)
2701 {
2702     MigrationState *s;
2703 
2704     s = migrate_get_current();
2705 
2706     return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2707 }
2708 
2709 bool migrate_use_return_path(void)
2710 {
2711     MigrationState *s;
2712 
2713     s = migrate_get_current();
2714 
2715     return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2716 }
2717 
2718 bool migrate_use_block_incremental(void)
2719 {
2720     MigrationState *s;
2721 
2722     s = migrate_get_current();
2723 
2724     return s->parameters.block_incremental;
2725 }
2726 
2727 bool migrate_background_snapshot(void)
2728 {
2729     MigrationState *s;
2730 
2731     s = migrate_get_current();
2732 
2733     return s->enabled_capabilities[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT];
2734 }
2735 
2736 bool migrate_postcopy_preempt(void)
2737 {
2738     MigrationState *s;
2739 
2740     s = migrate_get_current();
2741 
2742     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_PREEMPT];
2743 }
2744 
2745 /* migration thread support */
2746 /*
2747  * Something bad happened to the RP stream, mark an error
2748  * The caller shall print or trace something to indicate why
2749  */
2750 static void mark_source_rp_bad(MigrationState *s)
2751 {
2752     s->rp_state.error = true;
2753 }
2754 
2755 static struct rp_cmd_args {
2756     ssize_t     len; /* -1 = variable */
2757     const char *name;
2758 } rp_cmd_args[] = {
2759     [MIG_RP_MSG_INVALID]        = { .len = -1, .name = "INVALID" },
2760     [MIG_RP_MSG_SHUT]           = { .len =  4, .name = "SHUT" },
2761     [MIG_RP_MSG_PONG]           = { .len =  4, .name = "PONG" },
2762     [MIG_RP_MSG_REQ_PAGES]      = { .len = 12, .name = "REQ_PAGES" },
2763     [MIG_RP_MSG_REQ_PAGES_ID]   = { .len = -1, .name = "REQ_PAGES_ID" },
2764     [MIG_RP_MSG_RECV_BITMAP]    = { .len = -1, .name = "RECV_BITMAP" },
2765     [MIG_RP_MSG_RESUME_ACK]     = { .len =  4, .name = "RESUME_ACK" },
2766     [MIG_RP_MSG_MAX]            = { .len = -1, .name = "MAX" },
2767 };
2768 
2769 /*
2770  * Process a request for pages received on the return path,
2771  * We're allowed to send more than requested (e.g. to round to our page size)
2772  * and we don't need to send pages that have already been sent.
2773  */
2774 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2775                                        ram_addr_t start, size_t len)
2776 {
2777     long our_host_ps = qemu_real_host_page_size();
2778 
2779     trace_migrate_handle_rp_req_pages(rbname, start, len);
2780 
2781     /*
2782      * Since we currently insist on matching page sizes, just sanity check
2783      * we're being asked for whole host pages.
2784      */
2785     if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
2786         !QEMU_IS_ALIGNED(len, our_host_ps)) {
2787         error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2788                      " len: %zd", __func__, start, len);
2789         mark_source_rp_bad(ms);
2790         return;
2791     }
2792 
2793     if (ram_save_queue_pages(rbname, start, len)) {
2794         mark_source_rp_bad(ms);
2795     }
2796 }
2797 
2798 /* Return true to retry, false to quit */
2799 static bool postcopy_pause_return_path_thread(MigrationState *s)
2800 {
2801     trace_postcopy_pause_return_path();
2802 
2803     qemu_sem_wait(&s->postcopy_pause_rp_sem);
2804 
2805     trace_postcopy_pause_return_path_continued();
2806 
2807     return true;
2808 }
2809 
2810 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2811 {
2812     RAMBlock *block = qemu_ram_block_by_name(block_name);
2813 
2814     if (!block) {
2815         error_report("%s: invalid block name '%s'", __func__, block_name);
2816         return -EINVAL;
2817     }
2818 
2819     /* Fetch the received bitmap and refresh the dirty bitmap */
2820     return ram_dirty_bitmap_reload(s, block);
2821 }
2822 
2823 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2824 {
2825     trace_source_return_path_thread_resume_ack(value);
2826 
2827     if (value != MIGRATION_RESUME_ACK_VALUE) {
2828         error_report("%s: illegal resume_ack value %"PRIu32,
2829                      __func__, value);
2830         return -1;
2831     }
2832 
2833     /* Now both sides are active. */
2834     migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2835                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2836 
2837     /* Notify send thread that time to continue send pages */
2838     qemu_sem_post(&s->rp_state.rp_sem);
2839 
2840     return 0;
2841 }
2842 
2843 /* Release ms->rp_state.from_dst_file in a safe way */
2844 static void migration_release_from_dst_file(MigrationState *ms)
2845 {
2846     QEMUFile *file;
2847 
2848     WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2849         /*
2850          * Reset the from_dst_file pointer first before releasing it, as we
2851          * can't block within lock section
2852          */
2853         file = ms->rp_state.from_dst_file;
2854         ms->rp_state.from_dst_file = NULL;
2855     }
2856 
2857     qemu_fclose(file);
2858 }
2859 
2860 /*
2861  * Handles messages sent on the return path towards the source VM
2862  *
2863  */
2864 static void *source_return_path_thread(void *opaque)
2865 {
2866     MigrationState *ms = opaque;
2867     QEMUFile *rp = ms->rp_state.from_dst_file;
2868     uint16_t header_len, header_type;
2869     uint8_t buf[512];
2870     uint32_t tmp32, sibling_error;
2871     ram_addr_t start = 0; /* =0 to silence warning */
2872     size_t  len = 0, expected_len;
2873     int res;
2874 
2875     trace_source_return_path_thread_entry();
2876     rcu_register_thread();
2877 
2878 retry:
2879     while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2880            migration_is_setup_or_active(ms->state)) {
2881         trace_source_return_path_thread_loop_top();
2882         header_type = qemu_get_be16(rp);
2883         header_len = qemu_get_be16(rp);
2884 
2885         if (qemu_file_get_error(rp)) {
2886             mark_source_rp_bad(ms);
2887             goto out;
2888         }
2889 
2890         if (header_type >= MIG_RP_MSG_MAX ||
2891             header_type == MIG_RP_MSG_INVALID) {
2892             error_report("RP: Received invalid message 0x%04x length 0x%04x",
2893                          header_type, header_len);
2894             mark_source_rp_bad(ms);
2895             goto out;
2896         }
2897 
2898         if ((rp_cmd_args[header_type].len != -1 &&
2899             header_len != rp_cmd_args[header_type].len) ||
2900             header_len > sizeof(buf)) {
2901             error_report("RP: Received '%s' message (0x%04x) with"
2902                          "incorrect length %d expecting %zu",
2903                          rp_cmd_args[header_type].name, header_type, header_len,
2904                          (size_t)rp_cmd_args[header_type].len);
2905             mark_source_rp_bad(ms);
2906             goto out;
2907         }
2908 
2909         /* We know we've got a valid header by this point */
2910         res = qemu_get_buffer(rp, buf, header_len);
2911         if (res != header_len) {
2912             error_report("RP: Failed reading data for message 0x%04x"
2913                          " read %d expected %d",
2914                          header_type, res, header_len);
2915             mark_source_rp_bad(ms);
2916             goto out;
2917         }
2918 
2919         /* OK, we have the message and the data */
2920         switch (header_type) {
2921         case MIG_RP_MSG_SHUT:
2922             sibling_error = ldl_be_p(buf);
2923             trace_source_return_path_thread_shut(sibling_error);
2924             if (sibling_error) {
2925                 error_report("RP: Sibling indicated error %d", sibling_error);
2926                 mark_source_rp_bad(ms);
2927             }
2928             /*
2929              * We'll let the main thread deal with closing the RP
2930              * we could do a shutdown(2) on it, but we're the only user
2931              * anyway, so there's nothing gained.
2932              */
2933             goto out;
2934 
2935         case MIG_RP_MSG_PONG:
2936             tmp32 = ldl_be_p(buf);
2937             trace_source_return_path_thread_pong(tmp32);
2938             break;
2939 
2940         case MIG_RP_MSG_REQ_PAGES:
2941             start = ldq_be_p(buf);
2942             len = ldl_be_p(buf + 8);
2943             migrate_handle_rp_req_pages(ms, NULL, start, len);
2944             break;
2945 
2946         case MIG_RP_MSG_REQ_PAGES_ID:
2947             expected_len = 12 + 1; /* header + termination */
2948 
2949             if (header_len >= expected_len) {
2950                 start = ldq_be_p(buf);
2951                 len = ldl_be_p(buf + 8);
2952                 /* Now we expect an idstr */
2953                 tmp32 = buf[12]; /* Length of the following idstr */
2954                 buf[13 + tmp32] = '\0';
2955                 expected_len += tmp32;
2956             }
2957             if (header_len != expected_len) {
2958                 error_report("RP: Req_Page_id with length %d expecting %zd",
2959                              header_len, expected_len);
2960                 mark_source_rp_bad(ms);
2961                 goto out;
2962             }
2963             migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2964             break;
2965 
2966         case MIG_RP_MSG_RECV_BITMAP:
2967             if (header_len < 1) {
2968                 error_report("%s: missing block name", __func__);
2969                 mark_source_rp_bad(ms);
2970                 goto out;
2971             }
2972             /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2973             buf[buf[0] + 1] = '\0';
2974             if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2975                 mark_source_rp_bad(ms);
2976                 goto out;
2977             }
2978             break;
2979 
2980         case MIG_RP_MSG_RESUME_ACK:
2981             tmp32 = ldl_be_p(buf);
2982             if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2983                 mark_source_rp_bad(ms);
2984                 goto out;
2985             }
2986             break;
2987 
2988         default:
2989             break;
2990         }
2991     }
2992 
2993 out:
2994     res = qemu_file_get_error(rp);
2995     if (res) {
2996         if (res && migration_in_postcopy()) {
2997             /*
2998              * Maybe there is something we can do: it looks like a
2999              * network down issue, and we pause for a recovery.
3000              */
3001             migration_release_from_dst_file(ms);
3002             rp = NULL;
3003             if (postcopy_pause_return_path_thread(ms)) {
3004                 /*
3005                  * Reload rp, reset the rest.  Referencing it is safe since
3006                  * it's reset only by us above, or when migration completes
3007                  */
3008                 rp = ms->rp_state.from_dst_file;
3009                 ms->rp_state.error = false;
3010                 goto retry;
3011             }
3012         }
3013 
3014         trace_source_return_path_thread_bad_end();
3015         mark_source_rp_bad(ms);
3016     }
3017 
3018     trace_source_return_path_thread_end();
3019     migration_release_from_dst_file(ms);
3020     rcu_unregister_thread();
3021     return NULL;
3022 }
3023 
3024 static int open_return_path_on_source(MigrationState *ms,
3025                                       bool create_thread)
3026 {
3027     ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
3028     if (!ms->rp_state.from_dst_file) {
3029         return -1;
3030     }
3031 
3032     trace_open_return_path_on_source();
3033 
3034     if (!create_thread) {
3035         /* We're done */
3036         return 0;
3037     }
3038 
3039     qemu_thread_create(&ms->rp_state.rp_thread, "return path",
3040                        source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
3041     ms->rp_state.rp_thread_created = true;
3042 
3043     trace_open_return_path_on_source_continue();
3044 
3045     return 0;
3046 }
3047 
3048 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
3049 static int await_return_path_close_on_source(MigrationState *ms)
3050 {
3051     /*
3052      * If this is a normal exit then the destination will send a SHUT and the
3053      * rp_thread will exit, however if there's an error we need to cause
3054      * it to exit.
3055      */
3056     if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
3057         /*
3058          * shutdown(2), if we have it, will cause it to unblock if it's stuck
3059          * waiting for the destination.
3060          */
3061         qemu_file_shutdown(ms->rp_state.from_dst_file);
3062         mark_source_rp_bad(ms);
3063     }
3064     trace_await_return_path_close_on_source_joining();
3065     qemu_thread_join(&ms->rp_state.rp_thread);
3066     ms->rp_state.rp_thread_created = false;
3067     trace_await_return_path_close_on_source_close();
3068     return ms->rp_state.error;
3069 }
3070 
3071 /*
3072  * Switch from normal iteration to postcopy
3073  * Returns non-0 on error
3074  */
3075 static int postcopy_start(MigrationState *ms)
3076 {
3077     int ret;
3078     QIOChannelBuffer *bioc;
3079     QEMUFile *fb;
3080     int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3081     int64_t bandwidth = migrate_max_postcopy_bandwidth();
3082     bool restart_block = false;
3083     int cur_state = MIGRATION_STATUS_ACTIVE;
3084 
3085     if (postcopy_preempt_wait_channel(ms)) {
3086         migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
3087         return -1;
3088     }
3089 
3090     if (!migrate_pause_before_switchover()) {
3091         migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
3092                           MIGRATION_STATUS_POSTCOPY_ACTIVE);
3093     }
3094 
3095     trace_postcopy_start();
3096     qemu_mutex_lock_iothread();
3097     trace_postcopy_start_set_run();
3098 
3099     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3100     global_state_store();
3101     ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
3102     if (ret < 0) {
3103         goto fail;
3104     }
3105 
3106     ret = migration_maybe_pause(ms, &cur_state,
3107                                 MIGRATION_STATUS_POSTCOPY_ACTIVE);
3108     if (ret < 0) {
3109         goto fail;
3110     }
3111 
3112     ret = bdrv_inactivate_all();
3113     if (ret < 0) {
3114         goto fail;
3115     }
3116     restart_block = true;
3117 
3118     /*
3119      * Cause any non-postcopiable, but iterative devices to
3120      * send out their final data.
3121      */
3122     qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
3123 
3124     /*
3125      * in Finish migrate and with the io-lock held everything should
3126      * be quiet, but we've potentially still got dirty pages and we
3127      * need to tell the destination to throw any pages it's already received
3128      * that are dirty
3129      */
3130     if (migrate_postcopy_ram()) {
3131         ram_postcopy_send_discard_bitmap(ms);
3132     }
3133 
3134     /*
3135      * send rest of state - note things that are doing postcopy
3136      * will notice we're in POSTCOPY_ACTIVE and not actually
3137      * wrap their state up here
3138      */
3139     /* 0 max-postcopy-bandwidth means unlimited */
3140     if (!bandwidth) {
3141         qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
3142     } else {
3143         qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
3144     }
3145     if (migrate_postcopy_ram()) {
3146         /* Ping just for debugging, helps line traces up */
3147         qemu_savevm_send_ping(ms->to_dst_file, 2);
3148     }
3149 
3150     /*
3151      * While loading the device state we may trigger page transfer
3152      * requests and the fd must be free to process those, and thus
3153      * the destination must read the whole device state off the fd before
3154      * it starts processing it.  Unfortunately the ad-hoc migration format
3155      * doesn't allow the destination to know the size to read without fully
3156      * parsing it through each devices load-state code (especially the open
3157      * coded devices that use get/put).
3158      * So we wrap the device state up in a package with a length at the start;
3159      * to do this we use a qemu_buf to hold the whole of the device state.
3160      */
3161     bioc = qio_channel_buffer_new(4096);
3162     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
3163     fb = qemu_file_new_output(QIO_CHANNEL(bioc));
3164     object_unref(OBJECT(bioc));
3165 
3166     /*
3167      * Make sure the receiver can get incoming pages before we send the rest
3168      * of the state
3169      */
3170     qemu_savevm_send_postcopy_listen(fb);
3171 
3172     qemu_savevm_state_complete_precopy(fb, false, false);
3173     if (migrate_postcopy_ram()) {
3174         qemu_savevm_send_ping(fb, 3);
3175     }
3176 
3177     qemu_savevm_send_postcopy_run(fb);
3178 
3179     /* <><> end of stuff going into the package */
3180 
3181     /* Last point of recovery; as soon as we send the package the destination
3182      * can open devices and potentially start running.
3183      * Lets just check again we've not got any errors.
3184      */
3185     ret = qemu_file_get_error(ms->to_dst_file);
3186     if (ret) {
3187         error_report("postcopy_start: Migration stream errored (pre package)");
3188         goto fail_closefb;
3189     }
3190 
3191     restart_block = false;
3192 
3193     /* Now send that blob */
3194     if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
3195         goto fail_closefb;
3196     }
3197     qemu_fclose(fb);
3198 
3199     /* Send a notify to give a chance for anything that needs to happen
3200      * at the transition to postcopy and after the device state; in particular
3201      * spice needs to trigger a transition now
3202      */
3203     ms->postcopy_after_devices = true;
3204     notifier_list_notify(&migration_state_notifiers, ms);
3205 
3206     ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
3207 
3208     qemu_mutex_unlock_iothread();
3209 
3210     if (migrate_postcopy_ram()) {
3211         /*
3212          * Although this ping is just for debug, it could potentially be
3213          * used for getting a better measurement of downtime at the source.
3214          */
3215         qemu_savevm_send_ping(ms->to_dst_file, 4);
3216     }
3217 
3218     if (migrate_release_ram()) {
3219         ram_postcopy_migrated_memory_release(ms);
3220     }
3221 
3222     ret = qemu_file_get_error(ms->to_dst_file);
3223     if (ret) {
3224         error_report("postcopy_start: Migration stream errored");
3225         migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
3226                               MIGRATION_STATUS_FAILED);
3227     }
3228 
3229     trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
3230 
3231     return ret;
3232 
3233 fail_closefb:
3234     qemu_fclose(fb);
3235 fail:
3236     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
3237                           MIGRATION_STATUS_FAILED);
3238     if (restart_block) {
3239         /* A failure happened early enough that we know the destination hasn't
3240          * accessed block devices, so we're safe to recover.
3241          */
3242         Error *local_err = NULL;
3243 
3244         bdrv_activate_all(&local_err);
3245         if (local_err) {
3246             error_report_err(local_err);
3247         }
3248     }
3249     qemu_mutex_unlock_iothread();
3250     return -1;
3251 }
3252 
3253 /**
3254  * migration_maybe_pause: Pause if required to by
3255  * migrate_pause_before_switchover called with the iothread locked
3256  * Returns: 0 on success
3257  */
3258 static int migration_maybe_pause(MigrationState *s,
3259                                  int *current_active_state,
3260                                  int new_state)
3261 {
3262     if (!migrate_pause_before_switchover()) {
3263         return 0;
3264     }
3265 
3266     /* Since leaving this state is not atomic with posting the semaphore
3267      * it's possible that someone could have issued multiple migrate_continue
3268      * and the semaphore is incorrectly positive at this point;
3269      * the docs say it's undefined to reinit a semaphore that's already
3270      * init'd, so use timedwait to eat up any existing posts.
3271      */
3272     while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
3273         /* This block intentionally left blank */
3274     }
3275 
3276     /*
3277      * If the migration is cancelled when it is in the completion phase,
3278      * the migration state is set to MIGRATION_STATUS_CANCELLING.
3279      * So we don't need to wait a semaphore, otherwise we would always
3280      * wait for the 'pause_sem' semaphore.
3281      */
3282     if (s->state != MIGRATION_STATUS_CANCELLING) {
3283         qemu_mutex_unlock_iothread();
3284         migrate_set_state(&s->state, *current_active_state,
3285                           MIGRATION_STATUS_PRE_SWITCHOVER);
3286         qemu_sem_wait(&s->pause_sem);
3287         migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
3288                           new_state);
3289         *current_active_state = new_state;
3290         qemu_mutex_lock_iothread();
3291     }
3292 
3293     return s->state == new_state ? 0 : -EINVAL;
3294 }
3295 
3296 /**
3297  * migration_completion: Used by migration_thread when there's not much left.
3298  *   The caller 'breaks' the loop when this returns.
3299  *
3300  * @s: Current migration state
3301  */
3302 static void migration_completion(MigrationState *s)
3303 {
3304     int ret;
3305     int current_active_state = s->state;
3306 
3307     if (s->state == MIGRATION_STATUS_ACTIVE) {
3308         qemu_mutex_lock_iothread();
3309         s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3310         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3311         s->vm_was_running = runstate_is_running();
3312         ret = global_state_store();
3313 
3314         if (!ret) {
3315             bool inactivate = !migrate_colo_enabled();
3316             ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
3317             trace_migration_completion_vm_stop(ret);
3318             if (ret >= 0) {
3319                 ret = migration_maybe_pause(s, &current_active_state,
3320                                             MIGRATION_STATUS_DEVICE);
3321             }
3322             if (ret >= 0) {
3323                 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
3324                 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
3325                                                          inactivate);
3326             }
3327             if (inactivate && ret >= 0) {
3328                 s->block_inactive = true;
3329             }
3330         }
3331         qemu_mutex_unlock_iothread();
3332 
3333         if (ret < 0) {
3334             goto fail;
3335         }
3336     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3337         trace_migration_completion_postcopy_end();
3338 
3339         qemu_mutex_lock_iothread();
3340         qemu_savevm_state_complete_postcopy(s->to_dst_file);
3341         qemu_mutex_unlock_iothread();
3342 
3343         /* Shutdown the postcopy fast path thread */
3344         if (migrate_postcopy_preempt()) {
3345             postcopy_preempt_shutdown_file(s);
3346         }
3347 
3348         trace_migration_completion_postcopy_end_after_complete();
3349     } else {
3350         goto fail;
3351     }
3352 
3353     /*
3354      * If rp was opened we must clean up the thread before
3355      * cleaning everything else up (since if there are no failures
3356      * it will wait for the destination to send it's status in
3357      * a SHUT command).
3358      */
3359     if (s->rp_state.rp_thread_created) {
3360         int rp_error;
3361         trace_migration_return_path_end_before();
3362         rp_error = await_return_path_close_on_source(s);
3363         trace_migration_return_path_end_after(rp_error);
3364         if (rp_error) {
3365             goto fail_invalidate;
3366         }
3367     }
3368 
3369     if (qemu_file_get_error(s->to_dst_file)) {
3370         trace_migration_completion_file_err();
3371         goto fail_invalidate;
3372     }
3373 
3374     if (migrate_colo_enabled() && s->state == MIGRATION_STATUS_ACTIVE) {
3375         /* COLO does not support postcopy */
3376         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3377                           MIGRATION_STATUS_COLO);
3378     } else {
3379         migrate_set_state(&s->state, current_active_state,
3380                           MIGRATION_STATUS_COMPLETED);
3381     }
3382 
3383     return;
3384 
3385 fail_invalidate:
3386     /* If not doing postcopy, vm_start() will be called: let's regain
3387      * control on images.
3388      */
3389     if (s->state == MIGRATION_STATUS_ACTIVE ||
3390         s->state == MIGRATION_STATUS_DEVICE) {
3391         Error *local_err = NULL;
3392 
3393         qemu_mutex_lock_iothread();
3394         bdrv_activate_all(&local_err);
3395         if (local_err) {
3396             error_report_err(local_err);
3397         } else {
3398             s->block_inactive = false;
3399         }
3400         qemu_mutex_unlock_iothread();
3401     }
3402 
3403 fail:
3404     migrate_set_state(&s->state, current_active_state,
3405                       MIGRATION_STATUS_FAILED);
3406 }
3407 
3408 /**
3409  * bg_migration_completion: Used by bg_migration_thread when after all the
3410  *   RAM has been saved. The caller 'breaks' the loop when this returns.
3411  *
3412  * @s: Current migration state
3413  */
3414 static void bg_migration_completion(MigrationState *s)
3415 {
3416     int current_active_state = s->state;
3417 
3418     /*
3419      * Stop tracking RAM writes - un-protect memory, un-register UFFD
3420      * memory ranges, flush kernel wait queues and wake up threads
3421      * waiting for write fault to be resolved.
3422      */
3423     ram_write_tracking_stop();
3424 
3425     if (s->state == MIGRATION_STATUS_ACTIVE) {
3426         /*
3427          * By this moment we have RAM content saved into the migration stream.
3428          * The next step is to flush the non-RAM content (device state)
3429          * right after the ram content. The device state has been stored into
3430          * the temporary buffer before RAM saving started.
3431          */
3432         qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
3433         qemu_fflush(s->to_dst_file);
3434     } else if (s->state == MIGRATION_STATUS_CANCELLING) {
3435         goto fail;
3436     }
3437 
3438     if (qemu_file_get_error(s->to_dst_file)) {
3439         trace_migration_completion_file_err();
3440         goto fail;
3441     }
3442 
3443     migrate_set_state(&s->state, current_active_state,
3444                       MIGRATION_STATUS_COMPLETED);
3445     return;
3446 
3447 fail:
3448     migrate_set_state(&s->state, current_active_state,
3449                       MIGRATION_STATUS_FAILED);
3450 }
3451 
3452 bool migrate_colo_enabled(void)
3453 {
3454     MigrationState *s = migrate_get_current();
3455     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
3456 }
3457 
3458 typedef enum MigThrError {
3459     /* No error detected */
3460     MIG_THR_ERR_NONE = 0,
3461     /* Detected error, but resumed successfully */
3462     MIG_THR_ERR_RECOVERED = 1,
3463     /* Detected fatal error, need to exit */
3464     MIG_THR_ERR_FATAL = 2,
3465 } MigThrError;
3466 
3467 static int postcopy_resume_handshake(MigrationState *s)
3468 {
3469     qemu_savevm_send_postcopy_resume(s->to_dst_file);
3470 
3471     while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3472         qemu_sem_wait(&s->rp_state.rp_sem);
3473     }
3474 
3475     if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3476         return 0;
3477     }
3478 
3479     return -1;
3480 }
3481 
3482 /* Return zero if success, or <0 for error */
3483 static int postcopy_do_resume(MigrationState *s)
3484 {
3485     int ret;
3486 
3487     /*
3488      * Call all the resume_prepare() hooks, so that modules can be
3489      * ready for the migration resume.
3490      */
3491     ret = qemu_savevm_state_resume_prepare(s);
3492     if (ret) {
3493         error_report("%s: resume_prepare() failure detected: %d",
3494                      __func__, ret);
3495         return ret;
3496     }
3497 
3498     /*
3499      * Last handshake with destination on the resume (destination will
3500      * switch to postcopy-active afterwards)
3501      */
3502     ret = postcopy_resume_handshake(s);
3503     if (ret) {
3504         error_report("%s: handshake failed: %d", __func__, ret);
3505         return ret;
3506     }
3507 
3508     return 0;
3509 }
3510 
3511 /*
3512  * We don't return until we are in a safe state to continue current
3513  * postcopy migration.  Returns MIG_THR_ERR_RECOVERED if recovered, or
3514  * MIG_THR_ERR_FATAL if unrecovery failure happened.
3515  */
3516 static MigThrError postcopy_pause(MigrationState *s)
3517 {
3518     assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3519 
3520     while (true) {
3521         QEMUFile *file;
3522 
3523         /*
3524          * Current channel is possibly broken. Release it.  Note that this is
3525          * guaranteed even without lock because to_dst_file should only be
3526          * modified by the migration thread.  That also guarantees that the
3527          * unregister of yank is safe too without the lock.  It should be safe
3528          * even to be within the qemu_file_lock, but we didn't do that to avoid
3529          * taking more mutex (yank_lock) within qemu_file_lock.  TL;DR: we make
3530          * the qemu_file_lock critical section as small as possible.
3531          */
3532         assert(s->to_dst_file);
3533         migration_ioc_unregister_yank_from_file(s->to_dst_file);
3534         qemu_mutex_lock(&s->qemu_file_lock);
3535         file = s->to_dst_file;
3536         s->to_dst_file = NULL;
3537         qemu_mutex_unlock(&s->qemu_file_lock);
3538 
3539         qemu_file_shutdown(file);
3540         qemu_fclose(file);
3541 
3542         /*
3543          * Do the same to postcopy fast path socket too if there is.  No
3544          * locking needed because no racer as long as we do this before setting
3545          * status to paused.
3546          */
3547         if (s->postcopy_qemufile_src) {
3548             migration_ioc_unregister_yank_from_file(s->postcopy_qemufile_src);
3549             qemu_file_shutdown(s->postcopy_qemufile_src);
3550             qemu_fclose(s->postcopy_qemufile_src);
3551             s->postcopy_qemufile_src = NULL;
3552         }
3553 
3554         migrate_set_state(&s->state, s->state,
3555                           MIGRATION_STATUS_POSTCOPY_PAUSED);
3556 
3557         error_report("Detected IO failure for postcopy. "
3558                      "Migration paused.");
3559 
3560         /*
3561          * We wait until things fixed up. Then someone will setup the
3562          * status back for us.
3563          */
3564         while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3565             qemu_sem_wait(&s->postcopy_pause_sem);
3566         }
3567 
3568         if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3569             /* Woken up by a recover procedure. Give it a shot */
3570 
3571             if (postcopy_preempt_wait_channel(s)) {
3572                 /*
3573                  * Preempt enabled, and new channel create failed; loop
3574                  * back to wait for another recovery.
3575                  */
3576                 continue;
3577             }
3578 
3579             /*
3580              * Firstly, let's wake up the return path now, with a new
3581              * return path channel.
3582              */
3583             qemu_sem_post(&s->postcopy_pause_rp_sem);
3584 
3585             /* Do the resume logic */
3586             if (postcopy_do_resume(s) == 0) {
3587                 /* Let's continue! */
3588                 trace_postcopy_pause_continued();
3589                 return MIG_THR_ERR_RECOVERED;
3590             } else {
3591                 /*
3592                  * Something wrong happened during the recovery, let's
3593                  * pause again. Pause is always better than throwing
3594                  * data away.
3595                  */
3596                 continue;
3597             }
3598         } else {
3599             /* This is not right... Time to quit. */
3600             return MIG_THR_ERR_FATAL;
3601         }
3602     }
3603 }
3604 
3605 static MigThrError migration_detect_error(MigrationState *s)
3606 {
3607     int ret;
3608     int state = s->state;
3609     Error *local_error = NULL;
3610 
3611     if (state == MIGRATION_STATUS_CANCELLING ||
3612         state == MIGRATION_STATUS_CANCELLED) {
3613         /* End the migration, but don't set the state to failed */
3614         return MIG_THR_ERR_FATAL;
3615     }
3616 
3617     /*
3618      * Try to detect any file errors.  Note that postcopy_qemufile_src will
3619      * be NULL when postcopy preempt is not enabled.
3620      */
3621     ret = qemu_file_get_error_obj_any(s->to_dst_file,
3622                                       s->postcopy_qemufile_src,
3623                                       &local_error);
3624     if (!ret) {
3625         /* Everything is fine */
3626         assert(!local_error);
3627         return MIG_THR_ERR_NONE;
3628     }
3629 
3630     if (local_error) {
3631         migrate_set_error(s, local_error);
3632         error_free(local_error);
3633     }
3634 
3635     if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
3636         /*
3637          * For postcopy, we allow the network to be down for a
3638          * while. After that, it can be continued by a
3639          * recovery phase.
3640          */
3641         return postcopy_pause(s);
3642     } else {
3643         /*
3644          * For precopy (or postcopy with error outside IO), we fail
3645          * with no time.
3646          */
3647         migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3648         trace_migration_thread_file_err();
3649 
3650         /* Time to stop the migration, now. */
3651         return MIG_THR_ERR_FATAL;
3652     }
3653 }
3654 
3655 /* How many bytes have we transferred since the beginning of the migration */
3656 static uint64_t migration_total_bytes(MigrationState *s)
3657 {
3658     return qemu_file_total_transferred(s->to_dst_file) +
3659         ram_counters.multifd_bytes;
3660 }
3661 
3662 static void migration_calculate_complete(MigrationState *s)
3663 {
3664     uint64_t bytes = migration_total_bytes(s);
3665     int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3666     int64_t transfer_time;
3667 
3668     s->total_time = end_time - s->start_time;
3669     if (!s->downtime) {
3670         /*
3671          * It's still not set, so we are precopy migration.  For
3672          * postcopy, downtime is calculated during postcopy_start().
3673          */
3674         s->downtime = end_time - s->downtime_start;
3675     }
3676 
3677     transfer_time = s->total_time - s->setup_time;
3678     if (transfer_time) {
3679         s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3680     }
3681 }
3682 
3683 static void update_iteration_initial_status(MigrationState *s)
3684 {
3685     /*
3686      * Update these three fields at the same time to avoid mismatch info lead
3687      * wrong speed calculation.
3688      */
3689     s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3690     s->iteration_initial_bytes = migration_total_bytes(s);
3691     s->iteration_initial_pages = ram_get_total_transferred_pages();
3692 }
3693 
3694 static void migration_update_counters(MigrationState *s,
3695                                       int64_t current_time)
3696 {
3697     uint64_t transferred, transferred_pages, time_spent;
3698     uint64_t current_bytes; /* bytes transferred since the beginning */
3699     double bandwidth;
3700 
3701     if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3702         return;
3703     }
3704 
3705     current_bytes = migration_total_bytes(s);
3706     transferred = current_bytes - s->iteration_initial_bytes;
3707     time_spent = current_time - s->iteration_start_time;
3708     bandwidth = (double)transferred / time_spent;
3709     s->threshold_size = bandwidth * s->parameters.downtime_limit;
3710 
3711     s->mbps = (((double) transferred * 8.0) /
3712                ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3713 
3714     transferred_pages = ram_get_total_transferred_pages() -
3715                             s->iteration_initial_pages;
3716     s->pages_per_second = (double) transferred_pages /
3717                              (((double) time_spent / 1000.0));
3718 
3719     /*
3720      * if we haven't sent anything, we don't want to
3721      * recalculate. 10000 is a small enough number for our purposes
3722      */
3723     if (ram_counters.dirty_pages_rate && transferred > 10000) {
3724         s->expected_downtime = ram_counters.remaining / bandwidth;
3725     }
3726 
3727     qemu_file_reset_rate_limit(s->to_dst_file);
3728 
3729     update_iteration_initial_status(s);
3730 
3731     trace_migrate_transferred(transferred, time_spent,
3732                               bandwidth, s->threshold_size);
3733 }
3734 
3735 /* Migration thread iteration status */
3736 typedef enum {
3737     MIG_ITERATE_RESUME,         /* Resume current iteration */
3738     MIG_ITERATE_SKIP,           /* Skip current iteration */
3739     MIG_ITERATE_BREAK,          /* Break the loop */
3740 } MigIterateState;
3741 
3742 /*
3743  * Return true if continue to the next iteration directly, false
3744  * otherwise.
3745  */
3746 static MigIterateState migration_iteration_run(MigrationState *s)
3747 {
3748     uint64_t pending_size, pend_pre, pend_compat, pend_post;
3749     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3750 
3751     qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
3752                               &pend_compat, &pend_post);
3753     pending_size = pend_pre + pend_compat + pend_post;
3754 
3755     trace_migrate_pending(pending_size, s->threshold_size,
3756                           pend_pre, pend_compat, pend_post);
3757 
3758     if (pending_size && pending_size >= s->threshold_size) {
3759         /* Still a significant amount to transfer */
3760         if (!in_postcopy && pend_pre <= s->threshold_size &&
3761             qatomic_read(&s->start_postcopy)) {
3762             if (postcopy_start(s)) {
3763                 error_report("%s: postcopy failed to start", __func__);
3764             }
3765             return MIG_ITERATE_SKIP;
3766         }
3767         /* Just another iteration step */
3768         qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3769     } else {
3770         trace_migration_thread_low_pending(pending_size);
3771         migration_completion(s);
3772         return MIG_ITERATE_BREAK;
3773     }
3774 
3775     return MIG_ITERATE_RESUME;
3776 }
3777 
3778 static void migration_iteration_finish(MigrationState *s)
3779 {
3780     /* If we enabled cpu throttling for auto-converge, turn it off. */
3781     cpu_throttle_stop();
3782 
3783     qemu_mutex_lock_iothread();
3784     switch (s->state) {
3785     case MIGRATION_STATUS_COMPLETED:
3786         migration_calculate_complete(s);
3787         runstate_set(RUN_STATE_POSTMIGRATE);
3788         break;
3789     case MIGRATION_STATUS_COLO:
3790         if (!migrate_colo_enabled()) {
3791             error_report("%s: critical error: calling COLO code without "
3792                          "COLO enabled", __func__);
3793         }
3794         migrate_start_colo_process(s);
3795         s->vm_was_running = true;
3796         /* Fallthrough */
3797     case MIGRATION_STATUS_FAILED:
3798     case MIGRATION_STATUS_CANCELLED:
3799     case MIGRATION_STATUS_CANCELLING:
3800         if (s->vm_was_running) {
3801             if (!runstate_check(RUN_STATE_SHUTDOWN)) {
3802                 vm_start();
3803             }
3804         } else {
3805             if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3806                 runstate_set(RUN_STATE_POSTMIGRATE);
3807             }
3808         }
3809         break;
3810 
3811     default:
3812         /* Should not reach here, but if so, forgive the VM. */
3813         error_report("%s: Unknown ending state %d", __func__, s->state);
3814         break;
3815     }
3816     migrate_fd_cleanup_schedule(s);
3817     qemu_mutex_unlock_iothread();
3818 }
3819 
3820 static void bg_migration_iteration_finish(MigrationState *s)
3821 {
3822     qemu_mutex_lock_iothread();
3823     switch (s->state) {
3824     case MIGRATION_STATUS_COMPLETED:
3825         migration_calculate_complete(s);
3826         break;
3827 
3828     case MIGRATION_STATUS_ACTIVE:
3829     case MIGRATION_STATUS_FAILED:
3830     case MIGRATION_STATUS_CANCELLED:
3831     case MIGRATION_STATUS_CANCELLING:
3832         break;
3833 
3834     default:
3835         /* Should not reach here, but if so, forgive the VM. */
3836         error_report("%s: Unknown ending state %d", __func__, s->state);
3837         break;
3838     }
3839 
3840     migrate_fd_cleanup_schedule(s);
3841     qemu_mutex_unlock_iothread();
3842 }
3843 
3844 /*
3845  * Return true if continue to the next iteration directly, false
3846  * otherwise.
3847  */
3848 static MigIterateState bg_migration_iteration_run(MigrationState *s)
3849 {
3850     int res;
3851 
3852     res = qemu_savevm_state_iterate(s->to_dst_file, false);
3853     if (res > 0) {
3854         bg_migration_completion(s);
3855         return MIG_ITERATE_BREAK;
3856     }
3857 
3858     return MIG_ITERATE_RESUME;
3859 }
3860 
3861 void migration_make_urgent_request(void)
3862 {
3863     qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3864 }
3865 
3866 void migration_consume_urgent_request(void)
3867 {
3868     qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3869 }
3870 
3871 /* Returns true if the rate limiting was broken by an urgent request */
3872 bool migration_rate_limit(void)
3873 {
3874     int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3875     MigrationState *s = migrate_get_current();
3876 
3877     bool urgent = false;
3878     migration_update_counters(s, now);
3879     if (qemu_file_rate_limit(s->to_dst_file)) {
3880 
3881         if (qemu_file_get_error(s->to_dst_file)) {
3882             return false;
3883         }
3884         /*
3885          * Wait for a delay to do rate limiting OR
3886          * something urgent to post the semaphore.
3887          */
3888         int ms = s->iteration_start_time + BUFFER_DELAY - now;
3889         trace_migration_rate_limit_pre(ms);
3890         if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3891             /*
3892              * We were woken by one or more urgent things but
3893              * the timedwait will have consumed one of them.
3894              * The service routine for the urgent wake will dec
3895              * the semaphore itself for each item it consumes,
3896              * so add this one we just eat back.
3897              */
3898             qemu_sem_post(&s->rate_limit_sem);
3899             urgent = true;
3900         }
3901         trace_migration_rate_limit_post(urgent);
3902     }
3903     return urgent;
3904 }
3905 
3906 /*
3907  * if failover devices are present, wait they are completely
3908  * unplugged
3909  */
3910 
3911 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
3912                                     int new_state)
3913 {
3914     if (qemu_savevm_state_guest_unplug_pending()) {
3915         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
3916 
3917         while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3918                qemu_savevm_state_guest_unplug_pending()) {
3919             qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3920         }
3921         if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
3922             int timeout = 120; /* 30 seconds */
3923             /*
3924              * migration has been canceled
3925              * but as we have started an unplug we must wait the end
3926              * to be able to plug back the card
3927              */
3928             while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
3929                 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3930             }
3931             if (qemu_savevm_state_guest_unplug_pending() &&
3932                 !qtest_enabled()) {
3933                 warn_report("migration: partially unplugged device on "
3934                             "failure");
3935             }
3936         }
3937 
3938         migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
3939     } else {
3940         migrate_set_state(&s->state, old_state, new_state);
3941     }
3942 }
3943 
3944 /*
3945  * Master migration thread on the source VM.
3946  * It drives the migration and pumps the data down the outgoing channel.
3947  */
3948 static void *migration_thread(void *opaque)
3949 {
3950     MigrationState *s = opaque;
3951     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3952     MigThrError thr_error;
3953     bool urgent = false;
3954 
3955     rcu_register_thread();
3956 
3957     object_ref(OBJECT(s));
3958     update_iteration_initial_status(s);
3959 
3960     qemu_savevm_state_header(s->to_dst_file);
3961 
3962     /*
3963      * If we opened the return path, we need to make sure dst has it
3964      * opened as well.
3965      */
3966     if (s->rp_state.rp_thread_created) {
3967         /* Now tell the dest that it should open its end so it can reply */
3968         qemu_savevm_send_open_return_path(s->to_dst_file);
3969 
3970         /* And do a ping that will make stuff easier to debug */
3971         qemu_savevm_send_ping(s->to_dst_file, 1);
3972     }
3973 
3974     if (migrate_postcopy()) {
3975         /*
3976          * Tell the destination that we *might* want to do postcopy later;
3977          * if the other end can't do postcopy it should fail now, nice and
3978          * early.
3979          */
3980         qemu_savevm_send_postcopy_advise(s->to_dst_file);
3981     }
3982 
3983     if (migrate_colo_enabled()) {
3984         /* Notify migration destination that we enable COLO */
3985         qemu_savevm_send_colo_enable(s->to_dst_file);
3986     }
3987 
3988     qemu_savevm_state_setup(s->to_dst_file);
3989 
3990     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3991                                MIGRATION_STATUS_ACTIVE);
3992 
3993     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3994 
3995     trace_migration_thread_setup_complete();
3996 
3997     while (migration_is_active(s)) {
3998         if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3999             MigIterateState iter_state = migration_iteration_run(s);
4000             if (iter_state == MIG_ITERATE_SKIP) {
4001                 continue;
4002             } else if (iter_state == MIG_ITERATE_BREAK) {
4003                 break;
4004             }
4005         }
4006 
4007         /*
4008          * Try to detect any kind of failures, and see whether we
4009          * should stop the migration now.
4010          */
4011         thr_error = migration_detect_error(s);
4012         if (thr_error == MIG_THR_ERR_FATAL) {
4013             /* Stop migration */
4014             break;
4015         } else if (thr_error == MIG_THR_ERR_RECOVERED) {
4016             /*
4017              * Just recovered from a e.g. network failure, reset all
4018              * the local variables. This is important to avoid
4019              * breaking transferred_bytes and bandwidth calculation
4020              */
4021             update_iteration_initial_status(s);
4022         }
4023 
4024         urgent = migration_rate_limit();
4025     }
4026 
4027     trace_migration_thread_after_loop();
4028     migration_iteration_finish(s);
4029     object_unref(OBJECT(s));
4030     rcu_unregister_thread();
4031     return NULL;
4032 }
4033 
4034 static void bg_migration_vm_start_bh(void *opaque)
4035 {
4036     MigrationState *s = opaque;
4037 
4038     qemu_bh_delete(s->vm_start_bh);
4039     s->vm_start_bh = NULL;
4040 
4041     vm_start();
4042     s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
4043 }
4044 
4045 /**
4046  * Background snapshot thread, based on live migration code.
4047  * This is an alternative implementation of live migration mechanism
4048  * introduced specifically to support background snapshots.
4049  *
4050  * It takes advantage of userfault_fd write protection mechanism introduced
4051  * in v5.7 kernel. Compared to existing dirty page logging migration much
4052  * lesser stream traffic is produced resulting in smaller snapshot images,
4053  * simply cause of no page duplicates can get into the stream.
4054  *
4055  * Another key point is that generated vmstate stream reflects machine state
4056  * 'frozen' at the beginning of snapshot creation compared to dirty page logging
4057  * mechanism, which effectively results in that saved snapshot is the state of VM
4058  * at the end of the process.
4059  */
4060 static void *bg_migration_thread(void *opaque)
4061 {
4062     MigrationState *s = opaque;
4063     int64_t setup_start;
4064     MigThrError thr_error;
4065     QEMUFile *fb;
4066     bool early_fail = true;
4067 
4068     rcu_register_thread();
4069     object_ref(OBJECT(s));
4070 
4071     qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
4072 
4073     setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
4074     /*
4075      * We want to save vmstate for the moment when migration has been
4076      * initiated but also we want to save RAM content while VM is running.
4077      * The RAM content should appear first in the vmstate. So, we first
4078      * stash the non-RAM part of the vmstate to the temporary buffer,
4079      * then write RAM part of the vmstate to the migration stream
4080      * with vCPUs running and, finally, write stashed non-RAM part of
4081      * the vmstate from the buffer to the migration stream.
4082      */
4083     s->bioc = qio_channel_buffer_new(512 * 1024);
4084     qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
4085     fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
4086     object_unref(OBJECT(s->bioc));
4087 
4088     update_iteration_initial_status(s);
4089 
4090     /*
4091      * Prepare for tracking memory writes with UFFD-WP - populate
4092      * RAM pages before protecting.
4093      */
4094 #ifdef __linux__
4095     ram_write_tracking_prepare();
4096 #endif
4097 
4098     qemu_savevm_state_header(s->to_dst_file);
4099     qemu_savevm_state_setup(s->to_dst_file);
4100 
4101     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
4102                                MIGRATION_STATUS_ACTIVE);
4103 
4104     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
4105 
4106     trace_migration_thread_setup_complete();
4107     s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
4108 
4109     qemu_mutex_lock_iothread();
4110 
4111     /*
4112      * If VM is currently in suspended state, then, to make a valid runstate
4113      * transition in vm_stop_force_state() we need to wakeup it up.
4114      */
4115     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
4116     s->vm_was_running = runstate_is_running();
4117 
4118     if (global_state_store()) {
4119         goto fail;
4120     }
4121     /* Forcibly stop VM before saving state of vCPUs and devices */
4122     if (vm_stop_force_state(RUN_STATE_PAUSED)) {
4123         goto fail;
4124     }
4125     /*
4126      * Put vCPUs in sync with shadow context structures, then
4127      * save their state to channel-buffer along with devices.
4128      */
4129     cpu_synchronize_all_states();
4130     if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
4131         goto fail;
4132     }
4133     /*
4134      * Since we are going to get non-iterable state data directly
4135      * from s->bioc->data, explicit flush is needed here.
4136      */
4137     qemu_fflush(fb);
4138 
4139     /* Now initialize UFFD context and start tracking RAM writes */
4140     if (ram_write_tracking_start()) {
4141         goto fail;
4142     }
4143     early_fail = false;
4144 
4145     /*
4146      * Start VM from BH handler to avoid write-fault lock here.
4147      * UFFD-WP protection for the whole RAM is already enabled so
4148      * calling VM state change notifiers from vm_start() would initiate
4149      * writes to virtio VQs memory which is in write-protected region.
4150      */
4151     s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
4152     qemu_bh_schedule(s->vm_start_bh);
4153 
4154     qemu_mutex_unlock_iothread();
4155 
4156     while (migration_is_active(s)) {
4157         MigIterateState iter_state = bg_migration_iteration_run(s);
4158         if (iter_state == MIG_ITERATE_SKIP) {
4159             continue;
4160         } else if (iter_state == MIG_ITERATE_BREAK) {
4161             break;
4162         }
4163 
4164         /*
4165          * Try to detect any kind of failures, and see whether we
4166          * should stop the migration now.
4167          */
4168         thr_error = migration_detect_error(s);
4169         if (thr_error == MIG_THR_ERR_FATAL) {
4170             /* Stop migration */
4171             break;
4172         }
4173 
4174         migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
4175     }
4176 
4177     trace_migration_thread_after_loop();
4178 
4179 fail:
4180     if (early_fail) {
4181         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
4182                 MIGRATION_STATUS_FAILED);
4183         qemu_mutex_unlock_iothread();
4184     }
4185 
4186     bg_migration_iteration_finish(s);
4187 
4188     qemu_fclose(fb);
4189     object_unref(OBJECT(s));
4190     rcu_unregister_thread();
4191 
4192     return NULL;
4193 }
4194 
4195 void migrate_fd_connect(MigrationState *s, Error *error_in)
4196 {
4197     Error *local_err = NULL;
4198     int64_t rate_limit;
4199     bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
4200 
4201     /*
4202      * If there's a previous error, free it and prepare for another one.
4203      * Meanwhile if migration completes successfully, there won't have an error
4204      * dumped when calling migrate_fd_cleanup().
4205      */
4206     migrate_error_free(s);
4207 
4208     s->expected_downtime = s->parameters.downtime_limit;
4209     if (resume) {
4210         assert(s->cleanup_bh);
4211     } else {
4212         assert(!s->cleanup_bh);
4213         s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
4214     }
4215     if (error_in) {
4216         migrate_fd_error(s, error_in);
4217         if (resume) {
4218             /*
4219              * Don't do cleanup for resume if channel is invalid, but only dump
4220              * the error.  We wait for another channel connect from the user.
4221              * The error_report still gives HMP user a hint on what failed.
4222              * It's normally done in migrate_fd_cleanup(), but call it here
4223              * explicitly.
4224              */
4225             error_report_err(error_copy(s->error));
4226         } else {
4227             migrate_fd_cleanup(s);
4228         }
4229         return;
4230     }
4231 
4232     if (resume) {
4233         /* This is a resumed migration */
4234         rate_limit = s->parameters.max_postcopy_bandwidth /
4235             XFER_LIMIT_RATIO;
4236     } else {
4237         /* This is a fresh new migration */
4238         rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
4239 
4240         /* Notify before starting migration thread */
4241         notifier_list_notify(&migration_state_notifiers, s);
4242     }
4243 
4244     qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
4245     qemu_file_set_blocking(s->to_dst_file, true);
4246 
4247     /*
4248      * Open the return path. For postcopy, it is used exclusively. For
4249      * precopy, only if user specified "return-path" capability would
4250      * QEMU uses the return path.
4251      */
4252     if (migrate_postcopy_ram() || migrate_use_return_path()) {
4253         if (open_return_path_on_source(s, !resume)) {
4254             error_report("Unable to open return-path for postcopy");
4255             migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
4256             migrate_fd_cleanup(s);
4257             return;
4258         }
4259     }
4260 
4261     /* This needs to be done before resuming a postcopy */
4262     if (postcopy_preempt_setup(s, &local_err)) {
4263         error_report_err(local_err);
4264         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4265                           MIGRATION_STATUS_FAILED);
4266         migrate_fd_cleanup(s);
4267         return;
4268     }
4269 
4270     if (resume) {
4271         /* Wakeup the main migration thread to do the recovery */
4272         migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
4273                           MIGRATION_STATUS_POSTCOPY_RECOVER);
4274         qemu_sem_post(&s->postcopy_pause_sem);
4275         return;
4276     }
4277 
4278     if (multifd_save_setup(&local_err) != 0) {
4279         error_report_err(local_err);
4280         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4281                           MIGRATION_STATUS_FAILED);
4282         migrate_fd_cleanup(s);
4283         return;
4284     }
4285 
4286     if (migrate_background_snapshot()) {
4287         qemu_thread_create(&s->thread, "bg_snapshot",
4288                 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
4289     } else {
4290         qemu_thread_create(&s->thread, "live_migration",
4291                 migration_thread, s, QEMU_THREAD_JOINABLE);
4292     }
4293     s->migration_thread_running = true;
4294 }
4295 
4296 void migration_global_dump(Monitor *mon)
4297 {
4298     MigrationState *ms = migrate_get_current();
4299 
4300     monitor_printf(mon, "globals:\n");
4301     monitor_printf(mon, "store-global-state: %s\n",
4302                    ms->store_global_state ? "on" : "off");
4303     monitor_printf(mon, "only-migratable: %s\n",
4304                    only_migratable ? "on" : "off");
4305     monitor_printf(mon, "send-configuration: %s\n",
4306                    ms->send_configuration ? "on" : "off");
4307     monitor_printf(mon, "send-section-footer: %s\n",
4308                    ms->send_section_footer ? "on" : "off");
4309     monitor_printf(mon, "decompress-error-check: %s\n",
4310                    ms->decompress_error_check ? "on" : "off");
4311     monitor_printf(mon, "clear-bitmap-shift: %u\n",
4312                    ms->clear_bitmap_shift);
4313 }
4314 
4315 #define DEFINE_PROP_MIG_CAP(name, x)             \
4316     DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
4317 
4318 static Property migration_properties[] = {
4319     DEFINE_PROP_BOOL("store-global-state", MigrationState,
4320                      store_global_state, true),
4321     DEFINE_PROP_BOOL("send-configuration", MigrationState,
4322                      send_configuration, true),
4323     DEFINE_PROP_BOOL("send-section-footer", MigrationState,
4324                      send_section_footer, true),
4325     DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
4326                       decompress_error_check, true),
4327     DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
4328                       clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
4329 
4330     /* Migration parameters */
4331     DEFINE_PROP_UINT8("x-compress-level", MigrationState,
4332                       parameters.compress_level,
4333                       DEFAULT_MIGRATE_COMPRESS_LEVEL),
4334     DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
4335                       parameters.compress_threads,
4336                       DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
4337     DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
4338                       parameters.compress_wait_thread, true),
4339     DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
4340                       parameters.decompress_threads,
4341                       DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
4342     DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState,
4343                       parameters.throttle_trigger_threshold,
4344                       DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD),
4345     DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
4346                       parameters.cpu_throttle_initial,
4347                       DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
4348     DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
4349                       parameters.cpu_throttle_increment,
4350                       DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
4351     DEFINE_PROP_BOOL("x-cpu-throttle-tailslow", MigrationState,
4352                       parameters.cpu_throttle_tailslow, false),
4353     DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
4354                       parameters.max_bandwidth, MAX_THROTTLE),
4355     DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
4356                       parameters.downtime_limit,
4357                       DEFAULT_MIGRATE_SET_DOWNTIME),
4358     DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
4359                       parameters.x_checkpoint_delay,
4360                       DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
4361     DEFINE_PROP_UINT8("multifd-channels", MigrationState,
4362                       parameters.multifd_channels,
4363                       DEFAULT_MIGRATE_MULTIFD_CHANNELS),
4364     DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
4365                       parameters.multifd_compression,
4366                       DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
4367     DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
4368                       parameters.multifd_zlib_level,
4369                       DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
4370     DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
4371                       parameters.multifd_zstd_level,
4372                       DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
4373     DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
4374                       parameters.xbzrle_cache_size,
4375                       DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
4376     DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
4377                       parameters.max_postcopy_bandwidth,
4378                       DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
4379     DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
4380                       parameters.max_cpu_throttle,
4381                       DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
4382     DEFINE_PROP_SIZE("announce-initial", MigrationState,
4383                       parameters.announce_initial,
4384                       DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
4385     DEFINE_PROP_SIZE("announce-max", MigrationState,
4386                       parameters.announce_max,
4387                       DEFAULT_MIGRATE_ANNOUNCE_MAX),
4388     DEFINE_PROP_SIZE("announce-rounds", MigrationState,
4389                       parameters.announce_rounds,
4390                       DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
4391     DEFINE_PROP_SIZE("announce-step", MigrationState,
4392                       parameters.announce_step,
4393                       DEFAULT_MIGRATE_ANNOUNCE_STEP),
4394     DEFINE_PROP_BOOL("x-postcopy-preempt-break-huge", MigrationState,
4395                       postcopy_preempt_break_huge, true),
4396     DEFINE_PROP_STRING("tls-creds", MigrationState, parameters.tls_creds),
4397     DEFINE_PROP_STRING("tls-hostname", MigrationState, parameters.tls_hostname),
4398     DEFINE_PROP_STRING("tls-authz", MigrationState, parameters.tls_authz),
4399 
4400     /* Migration capabilities */
4401     DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
4402     DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
4403     DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
4404     DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
4405     DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
4406     DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
4407     DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
4408     DEFINE_PROP_MIG_CAP("x-postcopy-preempt",
4409                         MIGRATION_CAPABILITY_POSTCOPY_PREEMPT),
4410     DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
4411     DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
4412     DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
4413     DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
4414     DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
4415     DEFINE_PROP_MIG_CAP("x-background-snapshot",
4416             MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT),
4417 #ifdef CONFIG_LINUX
4418     DEFINE_PROP_MIG_CAP("x-zero-copy-send",
4419             MIGRATION_CAPABILITY_ZERO_COPY_SEND),
4420 #endif
4421 
4422     DEFINE_PROP_END_OF_LIST(),
4423 };
4424 
4425 static void migration_class_init(ObjectClass *klass, void *data)
4426 {
4427     DeviceClass *dc = DEVICE_CLASS(klass);
4428 
4429     dc->user_creatable = false;
4430     device_class_set_props(dc, migration_properties);
4431 }
4432 
4433 static void migration_instance_finalize(Object *obj)
4434 {
4435     MigrationState *ms = MIGRATION_OBJ(obj);
4436 
4437     qemu_mutex_destroy(&ms->error_mutex);
4438     qemu_mutex_destroy(&ms->qemu_file_lock);
4439     qemu_sem_destroy(&ms->wait_unplug_sem);
4440     qemu_sem_destroy(&ms->rate_limit_sem);
4441     qemu_sem_destroy(&ms->pause_sem);
4442     qemu_sem_destroy(&ms->postcopy_pause_sem);
4443     qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
4444     qemu_sem_destroy(&ms->rp_state.rp_sem);
4445     qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
4446     error_free(ms->error);
4447 }
4448 
4449 static void migration_instance_init(Object *obj)
4450 {
4451     MigrationState *ms = MIGRATION_OBJ(obj);
4452     MigrationParameters *params = &ms->parameters;
4453 
4454     ms->state = MIGRATION_STATUS_NONE;
4455     ms->mbps = -1;
4456     ms->pages_per_second = -1;
4457     qemu_sem_init(&ms->pause_sem, 0);
4458     qemu_mutex_init(&ms->error_mutex);
4459 
4460     params->tls_hostname = g_strdup("");
4461     params->tls_creds = g_strdup("");
4462 
4463     /* Set has_* up only for parameter checks */
4464     params->has_compress_level = true;
4465     params->has_compress_threads = true;
4466     params->has_compress_wait_thread = true;
4467     params->has_decompress_threads = true;
4468     params->has_throttle_trigger_threshold = true;
4469     params->has_cpu_throttle_initial = true;
4470     params->has_cpu_throttle_increment = true;
4471     params->has_cpu_throttle_tailslow = true;
4472     params->has_max_bandwidth = true;
4473     params->has_downtime_limit = true;
4474     params->has_x_checkpoint_delay = true;
4475     params->has_block_incremental = true;
4476     params->has_multifd_channels = true;
4477     params->has_multifd_compression = true;
4478     params->has_multifd_zlib_level = true;
4479     params->has_multifd_zstd_level = true;
4480     params->has_xbzrle_cache_size = true;
4481     params->has_max_postcopy_bandwidth = true;
4482     params->has_max_cpu_throttle = true;
4483     params->has_announce_initial = true;
4484     params->has_announce_max = true;
4485     params->has_announce_rounds = true;
4486     params->has_announce_step = true;
4487 
4488     qemu_sem_init(&ms->postcopy_pause_sem, 0);
4489     qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
4490     qemu_sem_init(&ms->rp_state.rp_sem, 0);
4491     qemu_sem_init(&ms->rate_limit_sem, 0);
4492     qemu_sem_init(&ms->wait_unplug_sem, 0);
4493     qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
4494     qemu_mutex_init(&ms->qemu_file_lock);
4495 }
4496 
4497 /*
4498  * Return true if check pass, false otherwise. Error will be put
4499  * inside errp if provided.
4500  */
4501 static bool migration_object_check(MigrationState *ms, Error **errp)
4502 {
4503     MigrationCapabilityStatusList *head = NULL;
4504     /* Assuming all off */
4505     bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
4506     int i;
4507 
4508     if (!migrate_params_check(&ms->parameters, errp)) {
4509         return false;
4510     }
4511 
4512     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
4513         if (ms->enabled_capabilities[i]) {
4514             QAPI_LIST_PREPEND(head, migrate_cap_add(i, true));
4515         }
4516     }
4517 
4518     ret = migrate_caps_check(cap_list, head, errp);
4519 
4520     /* It works with head == NULL */
4521     qapi_free_MigrationCapabilityStatusList(head);
4522 
4523     return ret;
4524 }
4525 
4526 static const TypeInfo migration_type = {
4527     .name = TYPE_MIGRATION,
4528     /*
4529      * NOTE: TYPE_MIGRATION is not really a device, as the object is
4530      * not created using qdev_new(), it is not attached to the qdev
4531      * device tree, and it is never realized.
4532      *
4533      * TODO: Make this TYPE_OBJECT once QOM provides something like
4534      * TYPE_DEVICE's "-global" properties.
4535      */
4536     .parent = TYPE_DEVICE,
4537     .class_init = migration_class_init,
4538     .class_size = sizeof(MigrationClass),
4539     .instance_size = sizeof(MigrationState),
4540     .instance_init = migration_instance_init,
4541     .instance_finalize = migration_instance_finalize,
4542 };
4543 
4544 static void register_migration_types(void)
4545 {
4546     type_register_static(&migration_type);
4547 }
4548 
4549 type_init(register_migration_types);
4550