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