xref: /qemu/migration/migration.c (revision 4b950af8)
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 
1937     qemu_savevm_state_cleanup();
1938 
1939     if (s->to_dst_file) {
1940         QEMUFile *tmp;
1941 
1942         trace_migrate_fd_cleanup();
1943         qemu_mutex_unlock_iothread();
1944         if (s->migration_thread_running) {
1945             qemu_thread_join(&s->thread);
1946             s->migration_thread_running = false;
1947         }
1948         qemu_mutex_lock_iothread();
1949 
1950         multifd_save_cleanup();
1951         qemu_mutex_lock(&s->qemu_file_lock);
1952         tmp = s->to_dst_file;
1953         s->to_dst_file = NULL;
1954         qemu_mutex_unlock(&s->qemu_file_lock);
1955         /*
1956          * Close the file handle without the lock to make sure the
1957          * critical section won't block for long.
1958          */
1959         migration_ioc_unregister_yank_from_file(tmp);
1960         qemu_fclose(tmp);
1961     }
1962 
1963     if (s->postcopy_qemufile_src) {
1964         migration_ioc_unregister_yank_from_file(s->postcopy_qemufile_src);
1965         qemu_fclose(s->postcopy_qemufile_src);
1966         s->postcopy_qemufile_src = NULL;
1967     }
1968 
1969     assert(!migration_is_active(s));
1970 
1971     if (s->state == MIGRATION_STATUS_CANCELLING) {
1972         migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1973                           MIGRATION_STATUS_CANCELLED);
1974     }
1975 
1976     if (s->error) {
1977         /* It is used on info migrate.  We can't free it */
1978         error_report_err(error_copy(s->error));
1979     }
1980     notifier_list_notify(&migration_state_notifiers, s);
1981     block_cleanup_parameters(s);
1982     yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1983 }
1984 
1985 static void migrate_fd_cleanup_schedule(MigrationState *s)
1986 {
1987     /*
1988      * Ref the state for bh, because it may be called when
1989      * there're already no other refs
1990      */
1991     object_ref(OBJECT(s));
1992     qemu_bh_schedule(s->cleanup_bh);
1993 }
1994 
1995 static void migrate_fd_cleanup_bh(void *opaque)
1996 {
1997     MigrationState *s = opaque;
1998     migrate_fd_cleanup(s);
1999     object_unref(OBJECT(s));
2000 }
2001 
2002 void migrate_set_error(MigrationState *s, const Error *error)
2003 {
2004     QEMU_LOCK_GUARD(&s->error_mutex);
2005     if (!s->error) {
2006         s->error = error_copy(error);
2007     }
2008 }
2009 
2010 static void migrate_error_free(MigrationState *s)
2011 {
2012     QEMU_LOCK_GUARD(&s->error_mutex);
2013     if (s->error) {
2014         error_free(s->error);
2015         s->error = NULL;
2016     }
2017 }
2018 
2019 void migrate_fd_error(MigrationState *s, const Error *error)
2020 {
2021     trace_migrate_fd_error(error_get_pretty(error));
2022     assert(s->to_dst_file == NULL);
2023     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2024                       MIGRATION_STATUS_FAILED);
2025     migrate_set_error(s, error);
2026 }
2027 
2028 static void migrate_fd_cancel(MigrationState *s)
2029 {
2030     int old_state ;
2031     QEMUFile *f = migrate_get_current()->to_dst_file;
2032     trace_migrate_fd_cancel();
2033 
2034     WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
2035         if (s->rp_state.from_dst_file) {
2036             /* shutdown the rp socket, so causing the rp thread to shutdown */
2037             qemu_file_shutdown(s->rp_state.from_dst_file);
2038         }
2039     }
2040 
2041     do {
2042         old_state = s->state;
2043         if (!migration_is_running(old_state)) {
2044             break;
2045         }
2046         /* If the migration is paused, kick it out of the pause */
2047         if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
2048             qemu_sem_post(&s->pause_sem);
2049         }
2050         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
2051     } while (s->state != MIGRATION_STATUS_CANCELLING);
2052 
2053     /*
2054      * If we're unlucky the migration code might be stuck somewhere in a
2055      * send/write while the network has failed and is waiting to timeout;
2056      * if we've got shutdown(2) available then we can force it to quit.
2057      * The outgoing qemu file gets closed in migrate_fd_cleanup that is
2058      * called in a bh, so there is no race against this cancel.
2059      */
2060     if (s->state == MIGRATION_STATUS_CANCELLING && f) {
2061         qemu_file_shutdown(f);
2062     }
2063     if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
2064         Error *local_err = NULL;
2065 
2066         bdrv_activate_all(&local_err);
2067         if (local_err) {
2068             error_report_err(local_err);
2069         } else {
2070             s->block_inactive = false;
2071         }
2072     }
2073 }
2074 
2075 void add_migration_state_change_notifier(Notifier *notify)
2076 {
2077     notifier_list_add(&migration_state_notifiers, notify);
2078 }
2079 
2080 void remove_migration_state_change_notifier(Notifier *notify)
2081 {
2082     notifier_remove(notify);
2083 }
2084 
2085 bool migration_in_setup(MigrationState *s)
2086 {
2087     return s->state == MIGRATION_STATUS_SETUP;
2088 }
2089 
2090 bool migration_has_finished(MigrationState *s)
2091 {
2092     return s->state == MIGRATION_STATUS_COMPLETED;
2093 }
2094 
2095 bool migration_has_failed(MigrationState *s)
2096 {
2097     return (s->state == MIGRATION_STATUS_CANCELLED ||
2098             s->state == MIGRATION_STATUS_FAILED);
2099 }
2100 
2101 bool migration_in_postcopy(void)
2102 {
2103     MigrationState *s = migrate_get_current();
2104 
2105     switch (s->state) {
2106     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
2107     case MIGRATION_STATUS_POSTCOPY_PAUSED:
2108     case MIGRATION_STATUS_POSTCOPY_RECOVER:
2109         return true;
2110     default:
2111         return false;
2112     }
2113 }
2114 
2115 bool migration_in_postcopy_after_devices(MigrationState *s)
2116 {
2117     return migration_in_postcopy() && s->postcopy_after_devices;
2118 }
2119 
2120 bool migration_in_incoming_postcopy(void)
2121 {
2122     PostcopyState ps = postcopy_state_get();
2123 
2124     return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
2125 }
2126 
2127 bool migration_in_bg_snapshot(void)
2128 {
2129     MigrationState *s = migrate_get_current();
2130 
2131     return migrate_background_snapshot() &&
2132             migration_is_setup_or_active(s->state);
2133 }
2134 
2135 bool migration_is_idle(void)
2136 {
2137     MigrationState *s = current_migration;
2138 
2139     if (!s) {
2140         return true;
2141     }
2142 
2143     switch (s->state) {
2144     case MIGRATION_STATUS_NONE:
2145     case MIGRATION_STATUS_CANCELLED:
2146     case MIGRATION_STATUS_COMPLETED:
2147     case MIGRATION_STATUS_FAILED:
2148         return true;
2149     case MIGRATION_STATUS_SETUP:
2150     case MIGRATION_STATUS_CANCELLING:
2151     case MIGRATION_STATUS_ACTIVE:
2152     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
2153     case MIGRATION_STATUS_COLO:
2154     case MIGRATION_STATUS_PRE_SWITCHOVER:
2155     case MIGRATION_STATUS_DEVICE:
2156     case MIGRATION_STATUS_WAIT_UNPLUG:
2157         return false;
2158     case MIGRATION_STATUS__MAX:
2159         g_assert_not_reached();
2160     }
2161 
2162     return false;
2163 }
2164 
2165 bool migration_is_active(MigrationState *s)
2166 {
2167     return (s->state == MIGRATION_STATUS_ACTIVE ||
2168             s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2169 }
2170 
2171 void migrate_init(MigrationState *s)
2172 {
2173     /*
2174      * Reinitialise all migration state, except
2175      * parameters/capabilities that the user set, and
2176      * locks.
2177      */
2178     s->cleanup_bh = 0;
2179     s->vm_start_bh = 0;
2180     s->to_dst_file = NULL;
2181     s->state = MIGRATION_STATUS_NONE;
2182     s->rp_state.from_dst_file = NULL;
2183     s->rp_state.error = false;
2184     s->mbps = 0.0;
2185     s->pages_per_second = 0.0;
2186     s->downtime = 0;
2187     s->expected_downtime = 0;
2188     s->setup_time = 0;
2189     s->start_postcopy = false;
2190     s->postcopy_after_devices = false;
2191     s->migration_thread_running = false;
2192     error_free(s->error);
2193     s->error = NULL;
2194     s->hostname = NULL;
2195 
2196     migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
2197 
2198     s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2199     s->total_time = 0;
2200     s->vm_was_running = false;
2201     s->iteration_initial_bytes = 0;
2202     s->threshold_size = 0;
2203 }
2204 
2205 int migrate_add_blocker_internal(Error *reason, Error **errp)
2206 {
2207     /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
2208     if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) {
2209         error_propagate_prepend(errp, error_copy(reason),
2210                                 "disallowing migration blocker "
2211                                 "(migration/snapshot in progress) for: ");
2212         return -EBUSY;
2213     }
2214 
2215     migration_blockers = g_slist_prepend(migration_blockers, reason);
2216     return 0;
2217 }
2218 
2219 int migrate_add_blocker(Error *reason, Error **errp)
2220 {
2221     if (only_migratable) {
2222         error_propagate_prepend(errp, error_copy(reason),
2223                                 "disallowing migration blocker "
2224                                 "(--only-migratable) for: ");
2225         return -EACCES;
2226     }
2227 
2228     return migrate_add_blocker_internal(reason, errp);
2229 }
2230 
2231 void migrate_del_blocker(Error *reason)
2232 {
2233     migration_blockers = g_slist_remove(migration_blockers, reason);
2234 }
2235 
2236 void qmp_migrate_incoming(const char *uri, Error **errp)
2237 {
2238     Error *local_err = NULL;
2239     static bool once = true;
2240 
2241     if (!once) {
2242         error_setg(errp, "The incoming migration has already been started");
2243         return;
2244     }
2245     if (!runstate_check(RUN_STATE_INMIGRATE)) {
2246         error_setg(errp, "'-incoming' was not specified on the command line");
2247         return;
2248     }
2249 
2250     if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2251         return;
2252     }
2253 
2254     qemu_start_incoming_migration(uri, &local_err);
2255 
2256     if (local_err) {
2257         yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2258         error_propagate(errp, local_err);
2259         return;
2260     }
2261 
2262     once = false;
2263 }
2264 
2265 void qmp_migrate_recover(const char *uri, Error **errp)
2266 {
2267     MigrationIncomingState *mis = migration_incoming_get_current();
2268 
2269     /*
2270      * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
2271      * callers (no one should ignore a recover failure); if there is, it's a
2272      * programming error.
2273      */
2274     assert(errp);
2275 
2276     if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2277         error_setg(errp, "Migrate recover can only be run "
2278                    "when postcopy is paused.");
2279         return;
2280     }
2281 
2282     /* If there's an existing transport, release it */
2283     migration_incoming_transport_cleanup(mis);
2284 
2285     /*
2286      * Note that this call will never start a real migration; it will
2287      * only re-setup the migration stream and poke existing migration
2288      * to continue using that newly established channel.
2289      */
2290     qemu_start_incoming_migration(uri, errp);
2291 }
2292 
2293 void qmp_migrate_pause(Error **errp)
2294 {
2295     MigrationState *ms = migrate_get_current();
2296     MigrationIncomingState *mis = migration_incoming_get_current();
2297     int ret;
2298 
2299     if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2300         /* Source side, during postcopy */
2301         qemu_mutex_lock(&ms->qemu_file_lock);
2302         ret = qemu_file_shutdown(ms->to_dst_file);
2303         qemu_mutex_unlock(&ms->qemu_file_lock);
2304         if (ret) {
2305             error_setg(errp, "Failed to pause source migration");
2306         }
2307         return;
2308     }
2309 
2310     if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2311         ret = qemu_file_shutdown(mis->from_src_file);
2312         if (ret) {
2313             error_setg(errp, "Failed to pause destination migration");
2314         }
2315         return;
2316     }
2317 
2318     error_setg(errp, "migrate-pause is currently only supported "
2319                "during postcopy-active state");
2320 }
2321 
2322 bool migration_is_blocked(Error **errp)
2323 {
2324     if (qemu_savevm_state_blocked(errp)) {
2325         return true;
2326     }
2327 
2328     if (migration_blockers) {
2329         error_propagate(errp, error_copy(migration_blockers->data));
2330         return true;
2331     }
2332 
2333     return false;
2334 }
2335 
2336 /* Returns true if continue to migrate, or false if error detected */
2337 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
2338                             bool resume, Error **errp)
2339 {
2340     Error *local_err = NULL;
2341 
2342     if (resume) {
2343         if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2344             error_setg(errp, "Cannot resume if there is no "
2345                        "paused migration");
2346             return false;
2347         }
2348 
2349         /*
2350          * Postcopy recovery won't work well with release-ram
2351          * capability since release-ram will drop the page buffer as
2352          * long as the page is put into the send buffer.  So if there
2353          * is a network failure happened, any page buffers that have
2354          * not yet reached the destination VM but have already been
2355          * sent from the source VM will be lost forever.  Let's refuse
2356          * the client from resuming such a postcopy migration.
2357          * Luckily release-ram was designed to only be used when src
2358          * and destination VMs are on the same host, so it should be
2359          * fine.
2360          */
2361         if (migrate_release_ram()) {
2362             error_setg(errp, "Postcopy recovery cannot work "
2363                        "when release-ram capability is set");
2364             return false;
2365         }
2366 
2367         /* This is a resume, skip init status */
2368         return true;
2369     }
2370 
2371     if (migration_is_running(s->state)) {
2372         error_setg(errp, QERR_MIGRATION_ACTIVE);
2373         return false;
2374     }
2375 
2376     if (runstate_check(RUN_STATE_INMIGRATE)) {
2377         error_setg(errp, "Guest is waiting for an incoming migration");
2378         return false;
2379     }
2380 
2381     if (runstate_check(RUN_STATE_POSTMIGRATE)) {
2382         error_setg(errp, "Can't migrate the vm that was paused due to "
2383                    "previous migration");
2384         return false;
2385     }
2386 
2387     if (migration_is_blocked(errp)) {
2388         return false;
2389     }
2390 
2391     if (blk || blk_inc) {
2392         if (migrate_colo_enabled()) {
2393             error_setg(errp, "No disk migration is required in COLO mode");
2394             return false;
2395         }
2396         if (migrate_use_block() || migrate_use_block_incremental()) {
2397             error_setg(errp, "Command options are incompatible with "
2398                        "current migration capabilities");
2399             return false;
2400         }
2401         migrate_set_block_enabled(true, &local_err);
2402         if (local_err) {
2403             error_propagate(errp, local_err);
2404             return false;
2405         }
2406         s->must_remove_block_options = true;
2407     }
2408 
2409     if (blk_inc) {
2410         migrate_set_block_incremental(s, true);
2411     }
2412 
2413     migrate_init(s);
2414     /*
2415      * set ram_counters compression_counters memory to zero for a
2416      * new migration
2417      */
2418     memset(&ram_counters, 0, sizeof(ram_counters));
2419     memset(&compression_counters, 0, sizeof(compression_counters));
2420 
2421     return true;
2422 }
2423 
2424 void qmp_migrate(const char *uri, bool has_blk, bool blk,
2425                  bool has_inc, bool inc, bool has_detach, bool detach,
2426                  bool has_resume, bool resume, Error **errp)
2427 {
2428     Error *local_err = NULL;
2429     MigrationState *s = migrate_get_current();
2430     const char *p = NULL;
2431 
2432     if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
2433                          has_resume && resume, errp)) {
2434         /* Error detected, put into errp */
2435         return;
2436     }
2437 
2438     if (!(has_resume && resume)) {
2439         if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2440             return;
2441         }
2442     }
2443 
2444     migrate_protocol_allow_multi_channels(false);
2445     if (strstart(uri, "tcp:", &p) ||
2446         strstart(uri, "unix:", NULL) ||
2447         strstart(uri, "vsock:", NULL)) {
2448         migrate_protocol_allow_multi_channels(true);
2449         socket_start_outgoing_migration(s, p ? p : uri, &local_err);
2450 #ifdef CONFIG_RDMA
2451     } else if (strstart(uri, "rdma:", &p)) {
2452         rdma_start_outgoing_migration(s, p, &local_err);
2453 #endif
2454     } else if (strstart(uri, "exec:", &p)) {
2455         exec_start_outgoing_migration(s, p, &local_err);
2456     } else if (strstart(uri, "fd:", &p)) {
2457         fd_start_outgoing_migration(s, p, &local_err);
2458     } else {
2459         if (!(has_resume && resume)) {
2460             yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2461         }
2462         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
2463                    "a valid migration protocol");
2464         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2465                           MIGRATION_STATUS_FAILED);
2466         block_cleanup_parameters(s);
2467         return;
2468     }
2469 
2470     if (local_err) {
2471         if (!(has_resume && resume)) {
2472             yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2473         }
2474         migrate_fd_error(s, local_err);
2475         error_propagate(errp, local_err);
2476         return;
2477     }
2478 }
2479 
2480 void qmp_migrate_cancel(Error **errp)
2481 {
2482     migration_cancel(NULL);
2483 }
2484 
2485 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2486 {
2487     MigrationState *s = migrate_get_current();
2488     if (s->state != state) {
2489         error_setg(errp,  "Migration not in expected state: %s",
2490                    MigrationStatus_str(s->state));
2491         return;
2492     }
2493     qemu_sem_post(&s->pause_sem);
2494 }
2495 
2496 bool migrate_release_ram(void)
2497 {
2498     MigrationState *s;
2499 
2500     s = migrate_get_current();
2501 
2502     return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2503 }
2504 
2505 bool migrate_postcopy_ram(void)
2506 {
2507     MigrationState *s;
2508 
2509     s = migrate_get_current();
2510 
2511     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
2512 }
2513 
2514 bool migrate_postcopy(void)
2515 {
2516     return migrate_postcopy_ram() || migrate_dirty_bitmaps();
2517 }
2518 
2519 bool migrate_auto_converge(void)
2520 {
2521     MigrationState *s;
2522 
2523     s = migrate_get_current();
2524 
2525     return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2526 }
2527 
2528 bool migrate_zero_blocks(void)
2529 {
2530     MigrationState *s;
2531 
2532     s = migrate_get_current();
2533 
2534     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2535 }
2536 
2537 bool migrate_postcopy_blocktime(void)
2538 {
2539     MigrationState *s;
2540 
2541     s = migrate_get_current();
2542 
2543     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2544 }
2545 
2546 bool migrate_use_compression(void)
2547 {
2548     MigrationState *s;
2549 
2550     s = migrate_get_current();
2551 
2552     return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
2553 }
2554 
2555 int migrate_compress_level(void)
2556 {
2557     MigrationState *s;
2558 
2559     s = migrate_get_current();
2560 
2561     return s->parameters.compress_level;
2562 }
2563 
2564 int migrate_compress_threads(void)
2565 {
2566     MigrationState *s;
2567 
2568     s = migrate_get_current();
2569 
2570     return s->parameters.compress_threads;
2571 }
2572 
2573 int migrate_compress_wait_thread(void)
2574 {
2575     MigrationState *s;
2576 
2577     s = migrate_get_current();
2578 
2579     return s->parameters.compress_wait_thread;
2580 }
2581 
2582 int migrate_decompress_threads(void)
2583 {
2584     MigrationState *s;
2585 
2586     s = migrate_get_current();
2587 
2588     return s->parameters.decompress_threads;
2589 }
2590 
2591 bool migrate_dirty_bitmaps(void)
2592 {
2593     MigrationState *s;
2594 
2595     s = migrate_get_current();
2596 
2597     return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2598 }
2599 
2600 bool migrate_ignore_shared(void)
2601 {
2602     MigrationState *s;
2603 
2604     s = migrate_get_current();
2605 
2606     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2607 }
2608 
2609 bool migrate_validate_uuid(void)
2610 {
2611     MigrationState *s;
2612 
2613     s = migrate_get_current();
2614 
2615     return s->enabled_capabilities[MIGRATION_CAPABILITY_VALIDATE_UUID];
2616 }
2617 
2618 bool migrate_use_events(void)
2619 {
2620     MigrationState *s;
2621 
2622     s = migrate_get_current();
2623 
2624     return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2625 }
2626 
2627 bool migrate_use_multifd(void)
2628 {
2629     MigrationState *s;
2630 
2631     s = migrate_get_current();
2632 
2633     return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
2634 }
2635 
2636 bool migrate_pause_before_switchover(void)
2637 {
2638     MigrationState *s;
2639 
2640     s = migrate_get_current();
2641 
2642     return s->enabled_capabilities[
2643         MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2644 }
2645 
2646 int migrate_multifd_channels(void)
2647 {
2648     MigrationState *s;
2649 
2650     s = migrate_get_current();
2651 
2652     return s->parameters.multifd_channels;
2653 }
2654 
2655 MultiFDCompression migrate_multifd_compression(void)
2656 {
2657     MigrationState *s;
2658 
2659     s = migrate_get_current();
2660 
2661     assert(s->parameters.multifd_compression < MULTIFD_COMPRESSION__MAX);
2662     return s->parameters.multifd_compression;
2663 }
2664 
2665 int migrate_multifd_zlib_level(void)
2666 {
2667     MigrationState *s;
2668 
2669     s = migrate_get_current();
2670 
2671     return s->parameters.multifd_zlib_level;
2672 }
2673 
2674 int migrate_multifd_zstd_level(void)
2675 {
2676     MigrationState *s;
2677 
2678     s = migrate_get_current();
2679 
2680     return s->parameters.multifd_zstd_level;
2681 }
2682 
2683 #ifdef CONFIG_LINUX
2684 bool migrate_use_zero_copy_send(void)
2685 {
2686     MigrationState *s;
2687 
2688     s = migrate_get_current();
2689 
2690     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_COPY_SEND];
2691 }
2692 #endif
2693 
2694 int migrate_use_tls(void)
2695 {
2696     MigrationState *s;
2697 
2698     s = migrate_get_current();
2699 
2700     return s->parameters.tls_creds && *s->parameters.tls_creds;
2701 }
2702 
2703 int migrate_use_xbzrle(void)
2704 {
2705     MigrationState *s;
2706 
2707     s = migrate_get_current();
2708 
2709     return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2710 }
2711 
2712 uint64_t migrate_xbzrle_cache_size(void)
2713 {
2714     MigrationState *s;
2715 
2716     s = migrate_get_current();
2717 
2718     return s->parameters.xbzrle_cache_size;
2719 }
2720 
2721 static int64_t migrate_max_postcopy_bandwidth(void)
2722 {
2723     MigrationState *s;
2724 
2725     s = migrate_get_current();
2726 
2727     return s->parameters.max_postcopy_bandwidth;
2728 }
2729 
2730 bool migrate_use_block(void)
2731 {
2732     MigrationState *s;
2733 
2734     s = migrate_get_current();
2735 
2736     return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2737 }
2738 
2739 bool migrate_use_return_path(void)
2740 {
2741     MigrationState *s;
2742 
2743     s = migrate_get_current();
2744 
2745     return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2746 }
2747 
2748 bool migrate_use_block_incremental(void)
2749 {
2750     MigrationState *s;
2751 
2752     s = migrate_get_current();
2753 
2754     return s->parameters.block_incremental;
2755 }
2756 
2757 bool migrate_background_snapshot(void)
2758 {
2759     MigrationState *s;
2760 
2761     s = migrate_get_current();
2762 
2763     return s->enabled_capabilities[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT];
2764 }
2765 
2766 bool migrate_postcopy_preempt(void)
2767 {
2768     MigrationState *s;
2769 
2770     s = migrate_get_current();
2771 
2772     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_PREEMPT];
2773 }
2774 
2775 /* migration thread support */
2776 /*
2777  * Something bad happened to the RP stream, mark an error
2778  * The caller shall print or trace something to indicate why
2779  */
2780 static void mark_source_rp_bad(MigrationState *s)
2781 {
2782     s->rp_state.error = true;
2783 }
2784 
2785 static struct rp_cmd_args {
2786     ssize_t     len; /* -1 = variable */
2787     const char *name;
2788 } rp_cmd_args[] = {
2789     [MIG_RP_MSG_INVALID]        = { .len = -1, .name = "INVALID" },
2790     [MIG_RP_MSG_SHUT]           = { .len =  4, .name = "SHUT" },
2791     [MIG_RP_MSG_PONG]           = { .len =  4, .name = "PONG" },
2792     [MIG_RP_MSG_REQ_PAGES]      = { .len = 12, .name = "REQ_PAGES" },
2793     [MIG_RP_MSG_REQ_PAGES_ID]   = { .len = -1, .name = "REQ_PAGES_ID" },
2794     [MIG_RP_MSG_RECV_BITMAP]    = { .len = -1, .name = "RECV_BITMAP" },
2795     [MIG_RP_MSG_RESUME_ACK]     = { .len =  4, .name = "RESUME_ACK" },
2796     [MIG_RP_MSG_MAX]            = { .len = -1, .name = "MAX" },
2797 };
2798 
2799 /*
2800  * Process a request for pages received on the return path,
2801  * We're allowed to send more than requested (e.g. to round to our page size)
2802  * and we don't need to send pages that have already been sent.
2803  */
2804 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2805                                        ram_addr_t start, size_t len)
2806 {
2807     long our_host_ps = qemu_real_host_page_size();
2808 
2809     trace_migrate_handle_rp_req_pages(rbname, start, len);
2810 
2811     /*
2812      * Since we currently insist on matching page sizes, just sanity check
2813      * we're being asked for whole host pages.
2814      */
2815     if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
2816         !QEMU_IS_ALIGNED(len, our_host_ps)) {
2817         error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2818                      " len: %zd", __func__, start, len);
2819         mark_source_rp_bad(ms);
2820         return;
2821     }
2822 
2823     if (ram_save_queue_pages(rbname, start, len)) {
2824         mark_source_rp_bad(ms);
2825     }
2826 }
2827 
2828 /* Return true to retry, false to quit */
2829 static bool postcopy_pause_return_path_thread(MigrationState *s)
2830 {
2831     trace_postcopy_pause_return_path();
2832 
2833     qemu_sem_wait(&s->postcopy_pause_rp_sem);
2834 
2835     trace_postcopy_pause_return_path_continued();
2836 
2837     return true;
2838 }
2839 
2840 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2841 {
2842     RAMBlock *block = qemu_ram_block_by_name(block_name);
2843 
2844     if (!block) {
2845         error_report("%s: invalid block name '%s'", __func__, block_name);
2846         return -EINVAL;
2847     }
2848 
2849     /* Fetch the received bitmap and refresh the dirty bitmap */
2850     return ram_dirty_bitmap_reload(s, block);
2851 }
2852 
2853 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2854 {
2855     trace_source_return_path_thread_resume_ack(value);
2856 
2857     if (value != MIGRATION_RESUME_ACK_VALUE) {
2858         error_report("%s: illegal resume_ack value %"PRIu32,
2859                      __func__, value);
2860         return -1;
2861     }
2862 
2863     /* Now both sides are active. */
2864     migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2865                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2866 
2867     /* Notify send thread that time to continue send pages */
2868     qemu_sem_post(&s->rp_state.rp_sem);
2869 
2870     return 0;
2871 }
2872 
2873 /*
2874  * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2875  * existed) in a safe way.
2876  */
2877 static void migration_release_dst_files(MigrationState *ms)
2878 {
2879     QEMUFile *file;
2880 
2881     WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2882         /*
2883          * Reset the from_dst_file pointer first before releasing it, as we
2884          * can't block within lock section
2885          */
2886         file = ms->rp_state.from_dst_file;
2887         ms->rp_state.from_dst_file = NULL;
2888     }
2889 
2890     /*
2891      * Do the same to postcopy fast path socket too if there is.  No
2892      * locking needed because this qemufile should only be managed by
2893      * return path thread.
2894      */
2895     if (ms->postcopy_qemufile_src) {
2896         migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
2897         qemu_file_shutdown(ms->postcopy_qemufile_src);
2898         qemu_fclose(ms->postcopy_qemufile_src);
2899         ms->postcopy_qemufile_src = NULL;
2900     }
2901 
2902     qemu_fclose(file);
2903 }
2904 
2905 /*
2906  * Handles messages sent on the return path towards the source VM
2907  *
2908  */
2909 static void *source_return_path_thread(void *opaque)
2910 {
2911     MigrationState *ms = opaque;
2912     QEMUFile *rp = ms->rp_state.from_dst_file;
2913     uint16_t header_len, header_type;
2914     uint8_t buf[512];
2915     uint32_t tmp32, sibling_error;
2916     ram_addr_t start = 0; /* =0 to silence warning */
2917     size_t  len = 0, expected_len;
2918     int res;
2919 
2920     trace_source_return_path_thread_entry();
2921     rcu_register_thread();
2922 
2923 retry:
2924     while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2925            migration_is_setup_or_active(ms->state)) {
2926         trace_source_return_path_thread_loop_top();
2927         header_type = qemu_get_be16(rp);
2928         header_len = qemu_get_be16(rp);
2929 
2930         if (qemu_file_get_error(rp)) {
2931             mark_source_rp_bad(ms);
2932             goto out;
2933         }
2934 
2935         if (header_type >= MIG_RP_MSG_MAX ||
2936             header_type == MIG_RP_MSG_INVALID) {
2937             error_report("RP: Received invalid message 0x%04x length 0x%04x",
2938                          header_type, header_len);
2939             mark_source_rp_bad(ms);
2940             goto out;
2941         }
2942 
2943         if ((rp_cmd_args[header_type].len != -1 &&
2944             header_len != rp_cmd_args[header_type].len) ||
2945             header_len > sizeof(buf)) {
2946             error_report("RP: Received '%s' message (0x%04x) with"
2947                          "incorrect length %d expecting %zu",
2948                          rp_cmd_args[header_type].name, header_type, header_len,
2949                          (size_t)rp_cmd_args[header_type].len);
2950             mark_source_rp_bad(ms);
2951             goto out;
2952         }
2953 
2954         /* We know we've got a valid header by this point */
2955         res = qemu_get_buffer(rp, buf, header_len);
2956         if (res != header_len) {
2957             error_report("RP: Failed reading data for message 0x%04x"
2958                          " read %d expected %d",
2959                          header_type, res, header_len);
2960             mark_source_rp_bad(ms);
2961             goto out;
2962         }
2963 
2964         /* OK, we have the message and the data */
2965         switch (header_type) {
2966         case MIG_RP_MSG_SHUT:
2967             sibling_error = ldl_be_p(buf);
2968             trace_source_return_path_thread_shut(sibling_error);
2969             if (sibling_error) {
2970                 error_report("RP: Sibling indicated error %d", sibling_error);
2971                 mark_source_rp_bad(ms);
2972             }
2973             /*
2974              * We'll let the main thread deal with closing the RP
2975              * we could do a shutdown(2) on it, but we're the only user
2976              * anyway, so there's nothing gained.
2977              */
2978             goto out;
2979 
2980         case MIG_RP_MSG_PONG:
2981             tmp32 = ldl_be_p(buf);
2982             trace_source_return_path_thread_pong(tmp32);
2983             break;
2984 
2985         case MIG_RP_MSG_REQ_PAGES:
2986             start = ldq_be_p(buf);
2987             len = ldl_be_p(buf + 8);
2988             migrate_handle_rp_req_pages(ms, NULL, start, len);
2989             break;
2990 
2991         case MIG_RP_MSG_REQ_PAGES_ID:
2992             expected_len = 12 + 1; /* header + termination */
2993 
2994             if (header_len >= expected_len) {
2995                 start = ldq_be_p(buf);
2996                 len = ldl_be_p(buf + 8);
2997                 /* Now we expect an idstr */
2998                 tmp32 = buf[12]; /* Length of the following idstr */
2999                 buf[13 + tmp32] = '\0';
3000                 expected_len += tmp32;
3001             }
3002             if (header_len != expected_len) {
3003                 error_report("RP: Req_Page_id with length %d expecting %zd",
3004                              header_len, expected_len);
3005                 mark_source_rp_bad(ms);
3006                 goto out;
3007             }
3008             migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
3009             break;
3010 
3011         case MIG_RP_MSG_RECV_BITMAP:
3012             if (header_len < 1) {
3013                 error_report("%s: missing block name", __func__);
3014                 mark_source_rp_bad(ms);
3015                 goto out;
3016             }
3017             /* Format: len (1B) + idstr (<255B). This ends the idstr. */
3018             buf[buf[0] + 1] = '\0';
3019             if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
3020                 mark_source_rp_bad(ms);
3021                 goto out;
3022             }
3023             break;
3024 
3025         case MIG_RP_MSG_RESUME_ACK:
3026             tmp32 = ldl_be_p(buf);
3027             if (migrate_handle_rp_resume_ack(ms, tmp32)) {
3028                 mark_source_rp_bad(ms);
3029                 goto out;
3030             }
3031             break;
3032 
3033         default:
3034             break;
3035         }
3036     }
3037 
3038 out:
3039     res = qemu_file_get_error(rp);
3040     if (res) {
3041         if (res && migration_in_postcopy()) {
3042             /*
3043              * Maybe there is something we can do: it looks like a
3044              * network down issue, and we pause for a recovery.
3045              */
3046             migration_release_dst_files(ms);
3047             rp = NULL;
3048             if (postcopy_pause_return_path_thread(ms)) {
3049                 /*
3050                  * Reload rp, reset the rest.  Referencing it is safe since
3051                  * it's reset only by us above, or when migration completes
3052                  */
3053                 rp = ms->rp_state.from_dst_file;
3054                 ms->rp_state.error = false;
3055                 goto retry;
3056             }
3057         }
3058 
3059         trace_source_return_path_thread_bad_end();
3060         mark_source_rp_bad(ms);
3061     }
3062 
3063     trace_source_return_path_thread_end();
3064     migration_release_dst_files(ms);
3065     rcu_unregister_thread();
3066     return NULL;
3067 }
3068 
3069 static int open_return_path_on_source(MigrationState *ms,
3070                                       bool create_thread)
3071 {
3072     ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
3073     if (!ms->rp_state.from_dst_file) {
3074         return -1;
3075     }
3076 
3077     trace_open_return_path_on_source();
3078 
3079     if (!create_thread) {
3080         /* We're done */
3081         return 0;
3082     }
3083 
3084     qemu_thread_create(&ms->rp_state.rp_thread, "return path",
3085                        source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
3086     ms->rp_state.rp_thread_created = true;
3087 
3088     trace_open_return_path_on_source_continue();
3089 
3090     return 0;
3091 }
3092 
3093 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
3094 static int await_return_path_close_on_source(MigrationState *ms)
3095 {
3096     /*
3097      * If this is a normal exit then the destination will send a SHUT and the
3098      * rp_thread will exit, however if there's an error we need to cause
3099      * it to exit.
3100      */
3101     if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
3102         /*
3103          * shutdown(2), if we have it, will cause it to unblock if it's stuck
3104          * waiting for the destination.
3105          */
3106         qemu_file_shutdown(ms->rp_state.from_dst_file);
3107         mark_source_rp_bad(ms);
3108     }
3109     trace_await_return_path_close_on_source_joining();
3110     qemu_thread_join(&ms->rp_state.rp_thread);
3111     ms->rp_state.rp_thread_created = false;
3112     trace_await_return_path_close_on_source_close();
3113     return ms->rp_state.error;
3114 }
3115 
3116 /*
3117  * Switch from normal iteration to postcopy
3118  * Returns non-0 on error
3119  */
3120 static int postcopy_start(MigrationState *ms)
3121 {
3122     int ret;
3123     QIOChannelBuffer *bioc;
3124     QEMUFile *fb;
3125     int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3126     int64_t bandwidth = migrate_max_postcopy_bandwidth();
3127     bool restart_block = false;
3128     int cur_state = MIGRATION_STATUS_ACTIVE;
3129 
3130     if (postcopy_preempt_wait_channel(ms)) {
3131         migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
3132         return -1;
3133     }
3134 
3135     if (!migrate_pause_before_switchover()) {
3136         migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
3137                           MIGRATION_STATUS_POSTCOPY_ACTIVE);
3138     }
3139 
3140     trace_postcopy_start();
3141     qemu_mutex_lock_iothread();
3142     trace_postcopy_start_set_run();
3143 
3144     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3145     global_state_store();
3146     ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
3147     if (ret < 0) {
3148         goto fail;
3149     }
3150 
3151     ret = migration_maybe_pause(ms, &cur_state,
3152                                 MIGRATION_STATUS_POSTCOPY_ACTIVE);
3153     if (ret < 0) {
3154         goto fail;
3155     }
3156 
3157     ret = bdrv_inactivate_all();
3158     if (ret < 0) {
3159         goto fail;
3160     }
3161     restart_block = true;
3162 
3163     /*
3164      * Cause any non-postcopiable, but iterative devices to
3165      * send out their final data.
3166      */
3167     qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
3168 
3169     /*
3170      * in Finish migrate and with the io-lock held everything should
3171      * be quiet, but we've potentially still got dirty pages and we
3172      * need to tell the destination to throw any pages it's already received
3173      * that are dirty
3174      */
3175     if (migrate_postcopy_ram()) {
3176         ram_postcopy_send_discard_bitmap(ms);
3177     }
3178 
3179     /*
3180      * send rest of state - note things that are doing postcopy
3181      * will notice we're in POSTCOPY_ACTIVE and not actually
3182      * wrap their state up here
3183      */
3184     /* 0 max-postcopy-bandwidth means unlimited */
3185     if (!bandwidth) {
3186         qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
3187     } else {
3188         qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
3189     }
3190     if (migrate_postcopy_ram()) {
3191         /* Ping just for debugging, helps line traces up */
3192         qemu_savevm_send_ping(ms->to_dst_file, 2);
3193     }
3194 
3195     /*
3196      * While loading the device state we may trigger page transfer
3197      * requests and the fd must be free to process those, and thus
3198      * the destination must read the whole device state off the fd before
3199      * it starts processing it.  Unfortunately the ad-hoc migration format
3200      * doesn't allow the destination to know the size to read without fully
3201      * parsing it through each devices load-state code (especially the open
3202      * coded devices that use get/put).
3203      * So we wrap the device state up in a package with a length at the start;
3204      * to do this we use a qemu_buf to hold the whole of the device state.
3205      */
3206     bioc = qio_channel_buffer_new(4096);
3207     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
3208     fb = qemu_file_new_output(QIO_CHANNEL(bioc));
3209     object_unref(OBJECT(bioc));
3210 
3211     /*
3212      * Make sure the receiver can get incoming pages before we send the rest
3213      * of the state
3214      */
3215     qemu_savevm_send_postcopy_listen(fb);
3216 
3217     qemu_savevm_state_complete_precopy(fb, false, false);
3218     if (migrate_postcopy_ram()) {
3219         qemu_savevm_send_ping(fb, 3);
3220     }
3221 
3222     qemu_savevm_send_postcopy_run(fb);
3223 
3224     /* <><> end of stuff going into the package */
3225 
3226     /* Last point of recovery; as soon as we send the package the destination
3227      * can open devices and potentially start running.
3228      * Lets just check again we've not got any errors.
3229      */
3230     ret = qemu_file_get_error(ms->to_dst_file);
3231     if (ret) {
3232         error_report("postcopy_start: Migration stream errored (pre package)");
3233         goto fail_closefb;
3234     }
3235 
3236     restart_block = false;
3237 
3238     /* Now send that blob */
3239     if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
3240         goto fail_closefb;
3241     }
3242     qemu_fclose(fb);
3243 
3244     /* Send a notify to give a chance for anything that needs to happen
3245      * at the transition to postcopy and after the device state; in particular
3246      * spice needs to trigger a transition now
3247      */
3248     ms->postcopy_after_devices = true;
3249     notifier_list_notify(&migration_state_notifiers, ms);
3250 
3251     ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
3252 
3253     qemu_mutex_unlock_iothread();
3254 
3255     if (migrate_postcopy_ram()) {
3256         /*
3257          * Although this ping is just for debug, it could potentially be
3258          * used for getting a better measurement of downtime at the source.
3259          */
3260         qemu_savevm_send_ping(ms->to_dst_file, 4);
3261     }
3262 
3263     if (migrate_release_ram()) {
3264         ram_postcopy_migrated_memory_release(ms);
3265     }
3266 
3267     ret = qemu_file_get_error(ms->to_dst_file);
3268     if (ret) {
3269         error_report("postcopy_start: Migration stream errored");
3270         migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
3271                               MIGRATION_STATUS_FAILED);
3272     }
3273 
3274     trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
3275 
3276     return ret;
3277 
3278 fail_closefb:
3279     qemu_fclose(fb);
3280 fail:
3281     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
3282                           MIGRATION_STATUS_FAILED);
3283     if (restart_block) {
3284         /* A failure happened early enough that we know the destination hasn't
3285          * accessed block devices, so we're safe to recover.
3286          */
3287         Error *local_err = NULL;
3288 
3289         bdrv_activate_all(&local_err);
3290         if (local_err) {
3291             error_report_err(local_err);
3292         }
3293     }
3294     qemu_mutex_unlock_iothread();
3295     return -1;
3296 }
3297 
3298 /**
3299  * migration_maybe_pause: Pause if required to by
3300  * migrate_pause_before_switchover called with the iothread locked
3301  * Returns: 0 on success
3302  */
3303 static int migration_maybe_pause(MigrationState *s,
3304                                  int *current_active_state,
3305                                  int new_state)
3306 {
3307     if (!migrate_pause_before_switchover()) {
3308         return 0;
3309     }
3310 
3311     /* Since leaving this state is not atomic with posting the semaphore
3312      * it's possible that someone could have issued multiple migrate_continue
3313      * and the semaphore is incorrectly positive at this point;
3314      * the docs say it's undefined to reinit a semaphore that's already
3315      * init'd, so use timedwait to eat up any existing posts.
3316      */
3317     while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
3318         /* This block intentionally left blank */
3319     }
3320 
3321     /*
3322      * If the migration is cancelled when it is in the completion phase,
3323      * the migration state is set to MIGRATION_STATUS_CANCELLING.
3324      * So we don't need to wait a semaphore, otherwise we would always
3325      * wait for the 'pause_sem' semaphore.
3326      */
3327     if (s->state != MIGRATION_STATUS_CANCELLING) {
3328         qemu_mutex_unlock_iothread();
3329         migrate_set_state(&s->state, *current_active_state,
3330                           MIGRATION_STATUS_PRE_SWITCHOVER);
3331         qemu_sem_wait(&s->pause_sem);
3332         migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
3333                           new_state);
3334         *current_active_state = new_state;
3335         qemu_mutex_lock_iothread();
3336     }
3337 
3338     return s->state == new_state ? 0 : -EINVAL;
3339 }
3340 
3341 /**
3342  * migration_completion: Used by migration_thread when there's not much left.
3343  *   The caller 'breaks' the loop when this returns.
3344  *
3345  * @s: Current migration state
3346  */
3347 static void migration_completion(MigrationState *s)
3348 {
3349     int ret;
3350     int current_active_state = s->state;
3351 
3352     if (s->state == MIGRATION_STATUS_ACTIVE) {
3353         qemu_mutex_lock_iothread();
3354         s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3355         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3356         s->vm_was_running = runstate_is_running();
3357         ret = global_state_store();
3358 
3359         if (!ret) {
3360             bool inactivate = !migrate_colo_enabled();
3361             ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
3362             trace_migration_completion_vm_stop(ret);
3363             if (ret >= 0) {
3364                 ret = migration_maybe_pause(s, &current_active_state,
3365                                             MIGRATION_STATUS_DEVICE);
3366             }
3367             if (ret >= 0) {
3368                 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
3369                 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
3370                                                          inactivate);
3371             }
3372             if (inactivate && ret >= 0) {
3373                 s->block_inactive = true;
3374             }
3375         }
3376         qemu_mutex_unlock_iothread();
3377 
3378         if (ret < 0) {
3379             goto fail;
3380         }
3381     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3382         trace_migration_completion_postcopy_end();
3383 
3384         qemu_mutex_lock_iothread();
3385         qemu_savevm_state_complete_postcopy(s->to_dst_file);
3386         qemu_mutex_unlock_iothread();
3387 
3388         /* Shutdown the postcopy fast path thread */
3389         if (migrate_postcopy_preempt()) {
3390             postcopy_preempt_shutdown_file(s);
3391         }
3392 
3393         trace_migration_completion_postcopy_end_after_complete();
3394     } else {
3395         goto fail;
3396     }
3397 
3398     /*
3399      * If rp was opened we must clean up the thread before
3400      * cleaning everything else up (since if there are no failures
3401      * it will wait for the destination to send it's status in
3402      * a SHUT command).
3403      */
3404     if (s->rp_state.rp_thread_created) {
3405         int rp_error;
3406         trace_migration_return_path_end_before();
3407         rp_error = await_return_path_close_on_source(s);
3408         trace_migration_return_path_end_after(rp_error);
3409         if (rp_error) {
3410             goto fail_invalidate;
3411         }
3412     }
3413 
3414     if (qemu_file_get_error(s->to_dst_file)) {
3415         trace_migration_completion_file_err();
3416         goto fail_invalidate;
3417     }
3418 
3419     if (migrate_colo_enabled() && s->state == MIGRATION_STATUS_ACTIVE) {
3420         /* COLO does not support postcopy */
3421         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3422                           MIGRATION_STATUS_COLO);
3423     } else {
3424         migrate_set_state(&s->state, current_active_state,
3425                           MIGRATION_STATUS_COMPLETED);
3426     }
3427 
3428     return;
3429 
3430 fail_invalidate:
3431     /* If not doing postcopy, vm_start() will be called: let's regain
3432      * control on images.
3433      */
3434     if (s->state == MIGRATION_STATUS_ACTIVE ||
3435         s->state == MIGRATION_STATUS_DEVICE) {
3436         Error *local_err = NULL;
3437 
3438         qemu_mutex_lock_iothread();
3439         bdrv_activate_all(&local_err);
3440         if (local_err) {
3441             error_report_err(local_err);
3442         } else {
3443             s->block_inactive = false;
3444         }
3445         qemu_mutex_unlock_iothread();
3446     }
3447 
3448 fail:
3449     migrate_set_state(&s->state, current_active_state,
3450                       MIGRATION_STATUS_FAILED);
3451 }
3452 
3453 /**
3454  * bg_migration_completion: Used by bg_migration_thread when after all the
3455  *   RAM has been saved. The caller 'breaks' the loop when this returns.
3456  *
3457  * @s: Current migration state
3458  */
3459 static void bg_migration_completion(MigrationState *s)
3460 {
3461     int current_active_state = s->state;
3462 
3463     /*
3464      * Stop tracking RAM writes - un-protect memory, un-register UFFD
3465      * memory ranges, flush kernel wait queues and wake up threads
3466      * waiting for write fault to be resolved.
3467      */
3468     ram_write_tracking_stop();
3469 
3470     if (s->state == MIGRATION_STATUS_ACTIVE) {
3471         /*
3472          * By this moment we have RAM content saved into the migration stream.
3473          * The next step is to flush the non-RAM content (device state)
3474          * right after the ram content. The device state has been stored into
3475          * the temporary buffer before RAM saving started.
3476          */
3477         qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
3478         qemu_fflush(s->to_dst_file);
3479     } else if (s->state == MIGRATION_STATUS_CANCELLING) {
3480         goto fail;
3481     }
3482 
3483     if (qemu_file_get_error(s->to_dst_file)) {
3484         trace_migration_completion_file_err();
3485         goto fail;
3486     }
3487 
3488     migrate_set_state(&s->state, current_active_state,
3489                       MIGRATION_STATUS_COMPLETED);
3490     return;
3491 
3492 fail:
3493     migrate_set_state(&s->state, current_active_state,
3494                       MIGRATION_STATUS_FAILED);
3495 }
3496 
3497 bool migrate_colo_enabled(void)
3498 {
3499     MigrationState *s = migrate_get_current();
3500     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
3501 }
3502 
3503 typedef enum MigThrError {
3504     /* No error detected */
3505     MIG_THR_ERR_NONE = 0,
3506     /* Detected error, but resumed successfully */
3507     MIG_THR_ERR_RECOVERED = 1,
3508     /* Detected fatal error, need to exit */
3509     MIG_THR_ERR_FATAL = 2,
3510 } MigThrError;
3511 
3512 static int postcopy_resume_handshake(MigrationState *s)
3513 {
3514     qemu_savevm_send_postcopy_resume(s->to_dst_file);
3515 
3516     while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3517         qemu_sem_wait(&s->rp_state.rp_sem);
3518     }
3519 
3520     if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3521         return 0;
3522     }
3523 
3524     return -1;
3525 }
3526 
3527 /* Return zero if success, or <0 for error */
3528 static int postcopy_do_resume(MigrationState *s)
3529 {
3530     int ret;
3531 
3532     /*
3533      * Call all the resume_prepare() hooks, so that modules can be
3534      * ready for the migration resume.
3535      */
3536     ret = qemu_savevm_state_resume_prepare(s);
3537     if (ret) {
3538         error_report("%s: resume_prepare() failure detected: %d",
3539                      __func__, ret);
3540         return ret;
3541     }
3542 
3543     /*
3544      * Last handshake with destination on the resume (destination will
3545      * switch to postcopy-active afterwards)
3546      */
3547     ret = postcopy_resume_handshake(s);
3548     if (ret) {
3549         error_report("%s: handshake failed: %d", __func__, ret);
3550         return ret;
3551     }
3552 
3553     return 0;
3554 }
3555 
3556 /*
3557  * We don't return until we are in a safe state to continue current
3558  * postcopy migration.  Returns MIG_THR_ERR_RECOVERED if recovered, or
3559  * MIG_THR_ERR_FATAL if unrecovery failure happened.
3560  */
3561 static MigThrError postcopy_pause(MigrationState *s)
3562 {
3563     assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3564 
3565     while (true) {
3566         QEMUFile *file;
3567 
3568         /*
3569          * Current channel is possibly broken. Release it.  Note that this is
3570          * guaranteed even without lock because to_dst_file should only be
3571          * modified by the migration thread.  That also guarantees that the
3572          * unregister of yank is safe too without the lock.  It should be safe
3573          * even to be within the qemu_file_lock, but we didn't do that to avoid
3574          * taking more mutex (yank_lock) within qemu_file_lock.  TL;DR: we make
3575          * the qemu_file_lock critical section as small as possible.
3576          */
3577         assert(s->to_dst_file);
3578         migration_ioc_unregister_yank_from_file(s->to_dst_file);
3579         qemu_mutex_lock(&s->qemu_file_lock);
3580         file = s->to_dst_file;
3581         s->to_dst_file = NULL;
3582         qemu_mutex_unlock(&s->qemu_file_lock);
3583 
3584         qemu_file_shutdown(file);
3585         qemu_fclose(file);
3586 
3587         migrate_set_state(&s->state, s->state,
3588                           MIGRATION_STATUS_POSTCOPY_PAUSED);
3589 
3590         error_report("Detected IO failure for postcopy. "
3591                      "Migration paused.");
3592 
3593         /*
3594          * We wait until things fixed up. Then someone will setup the
3595          * status back for us.
3596          */
3597         while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3598             qemu_sem_wait(&s->postcopy_pause_sem);
3599         }
3600 
3601         if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3602             /* Woken up by a recover procedure. Give it a shot */
3603 
3604             if (postcopy_preempt_wait_channel(s)) {
3605                 /*
3606                  * Preempt enabled, and new channel create failed; loop
3607                  * back to wait for another recovery.
3608                  */
3609                 continue;
3610             }
3611 
3612             /*
3613              * Firstly, let's wake up the return path now, with a new
3614              * return path channel.
3615              */
3616             qemu_sem_post(&s->postcopy_pause_rp_sem);
3617 
3618             /* Do the resume logic */
3619             if (postcopy_do_resume(s) == 0) {
3620                 /* Let's continue! */
3621                 trace_postcopy_pause_continued();
3622                 return MIG_THR_ERR_RECOVERED;
3623             } else {
3624                 /*
3625                  * Something wrong happened during the recovery, let's
3626                  * pause again. Pause is always better than throwing
3627                  * data away.
3628                  */
3629                 continue;
3630             }
3631         } else {
3632             /* This is not right... Time to quit. */
3633             return MIG_THR_ERR_FATAL;
3634         }
3635     }
3636 }
3637 
3638 static MigThrError migration_detect_error(MigrationState *s)
3639 {
3640     int ret;
3641     int state = s->state;
3642     Error *local_error = NULL;
3643 
3644     if (state == MIGRATION_STATUS_CANCELLING ||
3645         state == MIGRATION_STATUS_CANCELLED) {
3646         /* End the migration, but don't set the state to failed */
3647         return MIG_THR_ERR_FATAL;
3648     }
3649 
3650     /*
3651      * Try to detect any file errors.  Note that postcopy_qemufile_src will
3652      * be NULL when postcopy preempt is not enabled.
3653      */
3654     ret = qemu_file_get_error_obj_any(s->to_dst_file,
3655                                       s->postcopy_qemufile_src,
3656                                       &local_error);
3657     if (!ret) {
3658         /* Everything is fine */
3659         assert(!local_error);
3660         return MIG_THR_ERR_NONE;
3661     }
3662 
3663     if (local_error) {
3664         migrate_set_error(s, local_error);
3665         error_free(local_error);
3666     }
3667 
3668     if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
3669         /*
3670          * For postcopy, we allow the network to be down for a
3671          * while. After that, it can be continued by a
3672          * recovery phase.
3673          */
3674         return postcopy_pause(s);
3675     } else {
3676         /*
3677          * For precopy (or postcopy with error outside IO), we fail
3678          * with no time.
3679          */
3680         migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3681         trace_migration_thread_file_err();
3682 
3683         /* Time to stop the migration, now. */
3684         return MIG_THR_ERR_FATAL;
3685     }
3686 }
3687 
3688 /* How many bytes have we transferred since the beginning of the migration */
3689 static uint64_t migration_total_bytes(MigrationState *s)
3690 {
3691     return qemu_file_total_transferred(s->to_dst_file) +
3692         ram_counters.multifd_bytes;
3693 }
3694 
3695 static void migration_calculate_complete(MigrationState *s)
3696 {
3697     uint64_t bytes = migration_total_bytes(s);
3698     int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3699     int64_t transfer_time;
3700 
3701     s->total_time = end_time - s->start_time;
3702     if (!s->downtime) {
3703         /*
3704          * It's still not set, so we are precopy migration.  For
3705          * postcopy, downtime is calculated during postcopy_start().
3706          */
3707         s->downtime = end_time - s->downtime_start;
3708     }
3709 
3710     transfer_time = s->total_time - s->setup_time;
3711     if (transfer_time) {
3712         s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3713     }
3714 }
3715 
3716 static void update_iteration_initial_status(MigrationState *s)
3717 {
3718     /*
3719      * Update these three fields at the same time to avoid mismatch info lead
3720      * wrong speed calculation.
3721      */
3722     s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3723     s->iteration_initial_bytes = migration_total_bytes(s);
3724     s->iteration_initial_pages = ram_get_total_transferred_pages();
3725 }
3726 
3727 static void migration_update_counters(MigrationState *s,
3728                                       int64_t current_time)
3729 {
3730     uint64_t transferred, transferred_pages, time_spent;
3731     uint64_t current_bytes; /* bytes transferred since the beginning */
3732     double bandwidth;
3733 
3734     if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3735         return;
3736     }
3737 
3738     current_bytes = migration_total_bytes(s);
3739     transferred = current_bytes - s->iteration_initial_bytes;
3740     time_spent = current_time - s->iteration_start_time;
3741     bandwidth = (double)transferred / time_spent;
3742     s->threshold_size = bandwidth * s->parameters.downtime_limit;
3743 
3744     s->mbps = (((double) transferred * 8.0) /
3745                ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3746 
3747     transferred_pages = ram_get_total_transferred_pages() -
3748                             s->iteration_initial_pages;
3749     s->pages_per_second = (double) transferred_pages /
3750                              (((double) time_spent / 1000.0));
3751 
3752     /*
3753      * if we haven't sent anything, we don't want to
3754      * recalculate. 10000 is a small enough number for our purposes
3755      */
3756     if (ram_counters.dirty_pages_rate && transferred > 10000) {
3757         s->expected_downtime = ram_counters.remaining / bandwidth;
3758     }
3759 
3760     qemu_file_reset_rate_limit(s->to_dst_file);
3761 
3762     update_iteration_initial_status(s);
3763 
3764     trace_migrate_transferred(transferred, time_spent,
3765                               bandwidth, s->threshold_size);
3766 }
3767 
3768 /* Migration thread iteration status */
3769 typedef enum {
3770     MIG_ITERATE_RESUME,         /* Resume current iteration */
3771     MIG_ITERATE_SKIP,           /* Skip current iteration */
3772     MIG_ITERATE_BREAK,          /* Break the loop */
3773 } MigIterateState;
3774 
3775 /*
3776  * Return true if continue to the next iteration directly, false
3777  * otherwise.
3778  */
3779 static MigIterateState migration_iteration_run(MigrationState *s)
3780 {
3781     uint64_t pending_size, pend_pre, pend_compat, pend_post;
3782     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3783 
3784     qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
3785                               &pend_compat, &pend_post);
3786     pending_size = pend_pre + pend_compat + pend_post;
3787 
3788     trace_migrate_pending(pending_size, s->threshold_size,
3789                           pend_pre, pend_compat, pend_post);
3790 
3791     if (pending_size && pending_size >= s->threshold_size) {
3792         /* Still a significant amount to transfer */
3793         if (!in_postcopy && pend_pre <= s->threshold_size &&
3794             qatomic_read(&s->start_postcopy)) {
3795             if (postcopy_start(s)) {
3796                 error_report("%s: postcopy failed to start", __func__);
3797             }
3798             return MIG_ITERATE_SKIP;
3799         }
3800         /* Just another iteration step */
3801         qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3802     } else {
3803         trace_migration_thread_low_pending(pending_size);
3804         migration_completion(s);
3805         return MIG_ITERATE_BREAK;
3806     }
3807 
3808     return MIG_ITERATE_RESUME;
3809 }
3810 
3811 static void migration_iteration_finish(MigrationState *s)
3812 {
3813     /* If we enabled cpu throttling for auto-converge, turn it off. */
3814     cpu_throttle_stop();
3815 
3816     qemu_mutex_lock_iothread();
3817     switch (s->state) {
3818     case MIGRATION_STATUS_COMPLETED:
3819         migration_calculate_complete(s);
3820         runstate_set(RUN_STATE_POSTMIGRATE);
3821         break;
3822     case MIGRATION_STATUS_COLO:
3823         if (!migrate_colo_enabled()) {
3824             error_report("%s: critical error: calling COLO code without "
3825                          "COLO enabled", __func__);
3826         }
3827         migrate_start_colo_process(s);
3828         s->vm_was_running = true;
3829         /* Fallthrough */
3830     case MIGRATION_STATUS_FAILED:
3831     case MIGRATION_STATUS_CANCELLED:
3832     case MIGRATION_STATUS_CANCELLING:
3833         if (s->vm_was_running) {
3834             if (!runstate_check(RUN_STATE_SHUTDOWN)) {
3835                 vm_start();
3836             }
3837         } else {
3838             if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3839                 runstate_set(RUN_STATE_POSTMIGRATE);
3840             }
3841         }
3842         break;
3843 
3844     default:
3845         /* Should not reach here, but if so, forgive the VM. */
3846         error_report("%s: Unknown ending state %d", __func__, s->state);
3847         break;
3848     }
3849     migrate_fd_cleanup_schedule(s);
3850     qemu_mutex_unlock_iothread();
3851 }
3852 
3853 static void bg_migration_iteration_finish(MigrationState *s)
3854 {
3855     qemu_mutex_lock_iothread();
3856     switch (s->state) {
3857     case MIGRATION_STATUS_COMPLETED:
3858         migration_calculate_complete(s);
3859         break;
3860 
3861     case MIGRATION_STATUS_ACTIVE:
3862     case MIGRATION_STATUS_FAILED:
3863     case MIGRATION_STATUS_CANCELLED:
3864     case MIGRATION_STATUS_CANCELLING:
3865         break;
3866 
3867     default:
3868         /* Should not reach here, but if so, forgive the VM. */
3869         error_report("%s: Unknown ending state %d", __func__, s->state);
3870         break;
3871     }
3872 
3873     migrate_fd_cleanup_schedule(s);
3874     qemu_mutex_unlock_iothread();
3875 }
3876 
3877 /*
3878  * Return true if continue to the next iteration directly, false
3879  * otherwise.
3880  */
3881 static MigIterateState bg_migration_iteration_run(MigrationState *s)
3882 {
3883     int res;
3884 
3885     res = qemu_savevm_state_iterate(s->to_dst_file, false);
3886     if (res > 0) {
3887         bg_migration_completion(s);
3888         return MIG_ITERATE_BREAK;
3889     }
3890 
3891     return MIG_ITERATE_RESUME;
3892 }
3893 
3894 void migration_make_urgent_request(void)
3895 {
3896     qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3897 }
3898 
3899 void migration_consume_urgent_request(void)
3900 {
3901     qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3902 }
3903 
3904 /* Returns true if the rate limiting was broken by an urgent request */
3905 bool migration_rate_limit(void)
3906 {
3907     int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3908     MigrationState *s = migrate_get_current();
3909 
3910     bool urgent = false;
3911     migration_update_counters(s, now);
3912     if (qemu_file_rate_limit(s->to_dst_file)) {
3913 
3914         if (qemu_file_get_error(s->to_dst_file)) {
3915             return false;
3916         }
3917         /*
3918          * Wait for a delay to do rate limiting OR
3919          * something urgent to post the semaphore.
3920          */
3921         int ms = s->iteration_start_time + BUFFER_DELAY - now;
3922         trace_migration_rate_limit_pre(ms);
3923         if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3924             /*
3925              * We were woken by one or more urgent things but
3926              * the timedwait will have consumed one of them.
3927              * The service routine for the urgent wake will dec
3928              * the semaphore itself for each item it consumes,
3929              * so add this one we just eat back.
3930              */
3931             qemu_sem_post(&s->rate_limit_sem);
3932             urgent = true;
3933         }
3934         trace_migration_rate_limit_post(urgent);
3935     }
3936     return urgent;
3937 }
3938 
3939 /*
3940  * if failover devices are present, wait they are completely
3941  * unplugged
3942  */
3943 
3944 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
3945                                     int new_state)
3946 {
3947     if (qemu_savevm_state_guest_unplug_pending()) {
3948         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
3949 
3950         while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3951                qemu_savevm_state_guest_unplug_pending()) {
3952             qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3953         }
3954         if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
3955             int timeout = 120; /* 30 seconds */
3956             /*
3957              * migration has been canceled
3958              * but as we have started an unplug we must wait the end
3959              * to be able to plug back the card
3960              */
3961             while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
3962                 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3963             }
3964             if (qemu_savevm_state_guest_unplug_pending() &&
3965                 !qtest_enabled()) {
3966                 warn_report("migration: partially unplugged device on "
3967                             "failure");
3968             }
3969         }
3970 
3971         migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
3972     } else {
3973         migrate_set_state(&s->state, old_state, new_state);
3974     }
3975 }
3976 
3977 /*
3978  * Master migration thread on the source VM.
3979  * It drives the migration and pumps the data down the outgoing channel.
3980  */
3981 static void *migration_thread(void *opaque)
3982 {
3983     MigrationState *s = opaque;
3984     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3985     MigThrError thr_error;
3986     bool urgent = false;
3987 
3988     rcu_register_thread();
3989 
3990     object_ref(OBJECT(s));
3991     update_iteration_initial_status(s);
3992 
3993     qemu_savevm_state_header(s->to_dst_file);
3994 
3995     /*
3996      * If we opened the return path, we need to make sure dst has it
3997      * opened as well.
3998      */
3999     if (s->rp_state.rp_thread_created) {
4000         /* Now tell the dest that it should open its end so it can reply */
4001         qemu_savevm_send_open_return_path(s->to_dst_file);
4002 
4003         /* And do a ping that will make stuff easier to debug */
4004         qemu_savevm_send_ping(s->to_dst_file, 1);
4005     }
4006 
4007     if (migrate_postcopy()) {
4008         /*
4009          * Tell the destination that we *might* want to do postcopy later;
4010          * if the other end can't do postcopy it should fail now, nice and
4011          * early.
4012          */
4013         qemu_savevm_send_postcopy_advise(s->to_dst_file);
4014     }
4015 
4016     if (migrate_colo_enabled()) {
4017         /* Notify migration destination that we enable COLO */
4018         qemu_savevm_send_colo_enable(s->to_dst_file);
4019     }
4020 
4021     qemu_savevm_state_setup(s->to_dst_file);
4022 
4023     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
4024                                MIGRATION_STATUS_ACTIVE);
4025 
4026     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
4027 
4028     trace_migration_thread_setup_complete();
4029 
4030     while (migration_is_active(s)) {
4031         if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
4032             MigIterateState iter_state = migration_iteration_run(s);
4033             if (iter_state == MIG_ITERATE_SKIP) {
4034                 continue;
4035             } else if (iter_state == MIG_ITERATE_BREAK) {
4036                 break;
4037             }
4038         }
4039 
4040         /*
4041          * Try to detect any kind of failures, and see whether we
4042          * should stop the migration now.
4043          */
4044         thr_error = migration_detect_error(s);
4045         if (thr_error == MIG_THR_ERR_FATAL) {
4046             /* Stop migration */
4047             break;
4048         } else if (thr_error == MIG_THR_ERR_RECOVERED) {
4049             /*
4050              * Just recovered from a e.g. network failure, reset all
4051              * the local variables. This is important to avoid
4052              * breaking transferred_bytes and bandwidth calculation
4053              */
4054             update_iteration_initial_status(s);
4055         }
4056 
4057         urgent = migration_rate_limit();
4058     }
4059 
4060     trace_migration_thread_after_loop();
4061     migration_iteration_finish(s);
4062     object_unref(OBJECT(s));
4063     rcu_unregister_thread();
4064     return NULL;
4065 }
4066 
4067 static void bg_migration_vm_start_bh(void *opaque)
4068 {
4069     MigrationState *s = opaque;
4070 
4071     qemu_bh_delete(s->vm_start_bh);
4072     s->vm_start_bh = NULL;
4073 
4074     vm_start();
4075     s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
4076 }
4077 
4078 /**
4079  * Background snapshot thread, based on live migration code.
4080  * This is an alternative implementation of live migration mechanism
4081  * introduced specifically to support background snapshots.
4082  *
4083  * It takes advantage of userfault_fd write protection mechanism introduced
4084  * in v5.7 kernel. Compared to existing dirty page logging migration much
4085  * lesser stream traffic is produced resulting in smaller snapshot images,
4086  * simply cause of no page duplicates can get into the stream.
4087  *
4088  * Another key point is that generated vmstate stream reflects machine state
4089  * 'frozen' at the beginning of snapshot creation compared to dirty page logging
4090  * mechanism, which effectively results in that saved snapshot is the state of VM
4091  * at the end of the process.
4092  */
4093 static void *bg_migration_thread(void *opaque)
4094 {
4095     MigrationState *s = opaque;
4096     int64_t setup_start;
4097     MigThrError thr_error;
4098     QEMUFile *fb;
4099     bool early_fail = true;
4100 
4101     rcu_register_thread();
4102     object_ref(OBJECT(s));
4103 
4104     qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
4105 
4106     setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
4107     /*
4108      * We want to save vmstate for the moment when migration has been
4109      * initiated but also we want to save RAM content while VM is running.
4110      * The RAM content should appear first in the vmstate. So, we first
4111      * stash the non-RAM part of the vmstate to the temporary buffer,
4112      * then write RAM part of the vmstate to the migration stream
4113      * with vCPUs running and, finally, write stashed non-RAM part of
4114      * the vmstate from the buffer to the migration stream.
4115      */
4116     s->bioc = qio_channel_buffer_new(512 * 1024);
4117     qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
4118     fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
4119     object_unref(OBJECT(s->bioc));
4120 
4121     update_iteration_initial_status(s);
4122 
4123     /*
4124      * Prepare for tracking memory writes with UFFD-WP - populate
4125      * RAM pages before protecting.
4126      */
4127 #ifdef __linux__
4128     ram_write_tracking_prepare();
4129 #endif
4130 
4131     qemu_savevm_state_header(s->to_dst_file);
4132     qemu_savevm_state_setup(s->to_dst_file);
4133 
4134     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
4135                                MIGRATION_STATUS_ACTIVE);
4136 
4137     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
4138 
4139     trace_migration_thread_setup_complete();
4140     s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
4141 
4142     qemu_mutex_lock_iothread();
4143 
4144     /*
4145      * If VM is currently in suspended state, then, to make a valid runstate
4146      * transition in vm_stop_force_state() we need to wakeup it up.
4147      */
4148     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
4149     s->vm_was_running = runstate_is_running();
4150 
4151     if (global_state_store()) {
4152         goto fail;
4153     }
4154     /* Forcibly stop VM before saving state of vCPUs and devices */
4155     if (vm_stop_force_state(RUN_STATE_PAUSED)) {
4156         goto fail;
4157     }
4158     /*
4159      * Put vCPUs in sync with shadow context structures, then
4160      * save their state to channel-buffer along with devices.
4161      */
4162     cpu_synchronize_all_states();
4163     if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
4164         goto fail;
4165     }
4166     /*
4167      * Since we are going to get non-iterable state data directly
4168      * from s->bioc->data, explicit flush is needed here.
4169      */
4170     qemu_fflush(fb);
4171 
4172     /* Now initialize UFFD context and start tracking RAM writes */
4173     if (ram_write_tracking_start()) {
4174         goto fail;
4175     }
4176     early_fail = false;
4177 
4178     /*
4179      * Start VM from BH handler to avoid write-fault lock here.
4180      * UFFD-WP protection for the whole RAM is already enabled so
4181      * calling VM state change notifiers from vm_start() would initiate
4182      * writes to virtio VQs memory which is in write-protected region.
4183      */
4184     s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
4185     qemu_bh_schedule(s->vm_start_bh);
4186 
4187     qemu_mutex_unlock_iothread();
4188 
4189     while (migration_is_active(s)) {
4190         MigIterateState iter_state = bg_migration_iteration_run(s);
4191         if (iter_state == MIG_ITERATE_SKIP) {
4192             continue;
4193         } else if (iter_state == MIG_ITERATE_BREAK) {
4194             break;
4195         }
4196 
4197         /*
4198          * Try to detect any kind of failures, and see whether we
4199          * should stop the migration now.
4200          */
4201         thr_error = migration_detect_error(s);
4202         if (thr_error == MIG_THR_ERR_FATAL) {
4203             /* Stop migration */
4204             break;
4205         }
4206 
4207         migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
4208     }
4209 
4210     trace_migration_thread_after_loop();
4211 
4212 fail:
4213     if (early_fail) {
4214         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
4215                 MIGRATION_STATUS_FAILED);
4216         qemu_mutex_unlock_iothread();
4217     }
4218 
4219     bg_migration_iteration_finish(s);
4220 
4221     qemu_fclose(fb);
4222     object_unref(OBJECT(s));
4223     rcu_unregister_thread();
4224 
4225     return NULL;
4226 }
4227 
4228 void migrate_fd_connect(MigrationState *s, Error *error_in)
4229 {
4230     Error *local_err = NULL;
4231     int64_t rate_limit;
4232     bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
4233 
4234     /*
4235      * If there's a previous error, free it and prepare for another one.
4236      * Meanwhile if migration completes successfully, there won't have an error
4237      * dumped when calling migrate_fd_cleanup().
4238      */
4239     migrate_error_free(s);
4240 
4241     s->expected_downtime = s->parameters.downtime_limit;
4242     if (resume) {
4243         assert(s->cleanup_bh);
4244     } else {
4245         assert(!s->cleanup_bh);
4246         s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
4247     }
4248     if (error_in) {
4249         migrate_fd_error(s, error_in);
4250         if (resume) {
4251             /*
4252              * Don't do cleanup for resume if channel is invalid, but only dump
4253              * the error.  We wait for another channel connect from the user.
4254              * The error_report still gives HMP user a hint on what failed.
4255              * It's normally done in migrate_fd_cleanup(), but call it here
4256              * explicitly.
4257              */
4258             error_report_err(error_copy(s->error));
4259         } else {
4260             migrate_fd_cleanup(s);
4261         }
4262         return;
4263     }
4264 
4265     if (resume) {
4266         /* This is a resumed migration */
4267         rate_limit = s->parameters.max_postcopy_bandwidth /
4268             XFER_LIMIT_RATIO;
4269     } else {
4270         /* This is a fresh new migration */
4271         rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
4272 
4273         /* Notify before starting migration thread */
4274         notifier_list_notify(&migration_state_notifiers, s);
4275     }
4276 
4277     qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
4278     qemu_file_set_blocking(s->to_dst_file, true);
4279 
4280     /*
4281      * Open the return path. For postcopy, it is used exclusively. For
4282      * precopy, only if user specified "return-path" capability would
4283      * QEMU uses the return path.
4284      */
4285     if (migrate_postcopy_ram() || migrate_use_return_path()) {
4286         if (open_return_path_on_source(s, !resume)) {
4287             error_report("Unable to open return-path for postcopy");
4288             migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
4289             migrate_fd_cleanup(s);
4290             return;
4291         }
4292     }
4293 
4294     /* This needs to be done before resuming a postcopy */
4295     if (postcopy_preempt_setup(s, &local_err)) {
4296         error_report_err(local_err);
4297         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4298                           MIGRATION_STATUS_FAILED);
4299         migrate_fd_cleanup(s);
4300         return;
4301     }
4302 
4303     if (resume) {
4304         /* Wakeup the main migration thread to do the recovery */
4305         migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
4306                           MIGRATION_STATUS_POSTCOPY_RECOVER);
4307         qemu_sem_post(&s->postcopy_pause_sem);
4308         return;
4309     }
4310 
4311     if (multifd_save_setup(&local_err) != 0) {
4312         error_report_err(local_err);
4313         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4314                           MIGRATION_STATUS_FAILED);
4315         migrate_fd_cleanup(s);
4316         return;
4317     }
4318 
4319     if (migrate_background_snapshot()) {
4320         qemu_thread_create(&s->thread, "bg_snapshot",
4321                 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
4322     } else {
4323         qemu_thread_create(&s->thread, "live_migration",
4324                 migration_thread, s, QEMU_THREAD_JOINABLE);
4325     }
4326     s->migration_thread_running = true;
4327 }
4328 
4329 void migration_global_dump(Monitor *mon)
4330 {
4331     MigrationState *ms = migrate_get_current();
4332 
4333     monitor_printf(mon, "globals:\n");
4334     monitor_printf(mon, "store-global-state: %s\n",
4335                    ms->store_global_state ? "on" : "off");
4336     monitor_printf(mon, "only-migratable: %s\n",
4337                    only_migratable ? "on" : "off");
4338     monitor_printf(mon, "send-configuration: %s\n",
4339                    ms->send_configuration ? "on" : "off");
4340     monitor_printf(mon, "send-section-footer: %s\n",
4341                    ms->send_section_footer ? "on" : "off");
4342     monitor_printf(mon, "decompress-error-check: %s\n",
4343                    ms->decompress_error_check ? "on" : "off");
4344     monitor_printf(mon, "clear-bitmap-shift: %u\n",
4345                    ms->clear_bitmap_shift);
4346 }
4347 
4348 #define DEFINE_PROP_MIG_CAP(name, x)             \
4349     DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
4350 
4351 static Property migration_properties[] = {
4352     DEFINE_PROP_BOOL("store-global-state", MigrationState,
4353                      store_global_state, true),
4354     DEFINE_PROP_BOOL("send-configuration", MigrationState,
4355                      send_configuration, true),
4356     DEFINE_PROP_BOOL("send-section-footer", MigrationState,
4357                      send_section_footer, true),
4358     DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
4359                       decompress_error_check, true),
4360     DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
4361                       clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
4362 
4363     /* Migration parameters */
4364     DEFINE_PROP_UINT8("x-compress-level", MigrationState,
4365                       parameters.compress_level,
4366                       DEFAULT_MIGRATE_COMPRESS_LEVEL),
4367     DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
4368                       parameters.compress_threads,
4369                       DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
4370     DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
4371                       parameters.compress_wait_thread, true),
4372     DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
4373                       parameters.decompress_threads,
4374                       DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
4375     DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState,
4376                       parameters.throttle_trigger_threshold,
4377                       DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD),
4378     DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
4379                       parameters.cpu_throttle_initial,
4380                       DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
4381     DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
4382                       parameters.cpu_throttle_increment,
4383                       DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
4384     DEFINE_PROP_BOOL("x-cpu-throttle-tailslow", MigrationState,
4385                       parameters.cpu_throttle_tailslow, false),
4386     DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
4387                       parameters.max_bandwidth, MAX_THROTTLE),
4388     DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
4389                       parameters.downtime_limit,
4390                       DEFAULT_MIGRATE_SET_DOWNTIME),
4391     DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
4392                       parameters.x_checkpoint_delay,
4393                       DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
4394     DEFINE_PROP_UINT8("multifd-channels", MigrationState,
4395                       parameters.multifd_channels,
4396                       DEFAULT_MIGRATE_MULTIFD_CHANNELS),
4397     DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
4398                       parameters.multifd_compression,
4399                       DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
4400     DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
4401                       parameters.multifd_zlib_level,
4402                       DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
4403     DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
4404                       parameters.multifd_zstd_level,
4405                       DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
4406     DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
4407                       parameters.xbzrle_cache_size,
4408                       DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
4409     DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
4410                       parameters.max_postcopy_bandwidth,
4411                       DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
4412     DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
4413                       parameters.max_cpu_throttle,
4414                       DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
4415     DEFINE_PROP_SIZE("announce-initial", MigrationState,
4416                       parameters.announce_initial,
4417                       DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
4418     DEFINE_PROP_SIZE("announce-max", MigrationState,
4419                       parameters.announce_max,
4420                       DEFAULT_MIGRATE_ANNOUNCE_MAX),
4421     DEFINE_PROP_SIZE("announce-rounds", MigrationState,
4422                       parameters.announce_rounds,
4423                       DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
4424     DEFINE_PROP_SIZE("announce-step", MigrationState,
4425                       parameters.announce_step,
4426                       DEFAULT_MIGRATE_ANNOUNCE_STEP),
4427     DEFINE_PROP_STRING("tls-creds", MigrationState, parameters.tls_creds),
4428     DEFINE_PROP_STRING("tls-hostname", MigrationState, parameters.tls_hostname),
4429     DEFINE_PROP_STRING("tls-authz", MigrationState, parameters.tls_authz),
4430 
4431     /* Migration capabilities */
4432     DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
4433     DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
4434     DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
4435     DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
4436     DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
4437     DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
4438     DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
4439     DEFINE_PROP_MIG_CAP("x-postcopy-preempt",
4440                         MIGRATION_CAPABILITY_POSTCOPY_PREEMPT),
4441     DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
4442     DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
4443     DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
4444     DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
4445     DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
4446     DEFINE_PROP_MIG_CAP("x-background-snapshot",
4447             MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT),
4448 #ifdef CONFIG_LINUX
4449     DEFINE_PROP_MIG_CAP("x-zero-copy-send",
4450             MIGRATION_CAPABILITY_ZERO_COPY_SEND),
4451 #endif
4452 
4453     DEFINE_PROP_END_OF_LIST(),
4454 };
4455 
4456 static void migration_class_init(ObjectClass *klass, void *data)
4457 {
4458     DeviceClass *dc = DEVICE_CLASS(klass);
4459 
4460     dc->user_creatable = false;
4461     device_class_set_props(dc, migration_properties);
4462 }
4463 
4464 static void migration_instance_finalize(Object *obj)
4465 {
4466     MigrationState *ms = MIGRATION_OBJ(obj);
4467 
4468     qemu_mutex_destroy(&ms->error_mutex);
4469     qemu_mutex_destroy(&ms->qemu_file_lock);
4470     qemu_sem_destroy(&ms->wait_unplug_sem);
4471     qemu_sem_destroy(&ms->rate_limit_sem);
4472     qemu_sem_destroy(&ms->pause_sem);
4473     qemu_sem_destroy(&ms->postcopy_pause_sem);
4474     qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
4475     qemu_sem_destroy(&ms->rp_state.rp_sem);
4476     qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
4477     error_free(ms->error);
4478 }
4479 
4480 static void migration_instance_init(Object *obj)
4481 {
4482     MigrationState *ms = MIGRATION_OBJ(obj);
4483     MigrationParameters *params = &ms->parameters;
4484 
4485     ms->state = MIGRATION_STATUS_NONE;
4486     ms->mbps = -1;
4487     ms->pages_per_second = -1;
4488     qemu_sem_init(&ms->pause_sem, 0);
4489     qemu_mutex_init(&ms->error_mutex);
4490 
4491     params->tls_hostname = g_strdup("");
4492     params->tls_creds = g_strdup("");
4493 
4494     /* Set has_* up only for parameter checks */
4495     params->has_compress_level = true;
4496     params->has_compress_threads = true;
4497     params->has_compress_wait_thread = true;
4498     params->has_decompress_threads = true;
4499     params->has_throttle_trigger_threshold = true;
4500     params->has_cpu_throttle_initial = true;
4501     params->has_cpu_throttle_increment = true;
4502     params->has_cpu_throttle_tailslow = true;
4503     params->has_max_bandwidth = true;
4504     params->has_downtime_limit = true;
4505     params->has_x_checkpoint_delay = true;
4506     params->has_block_incremental = true;
4507     params->has_multifd_channels = true;
4508     params->has_multifd_compression = true;
4509     params->has_multifd_zlib_level = true;
4510     params->has_multifd_zstd_level = true;
4511     params->has_xbzrle_cache_size = true;
4512     params->has_max_postcopy_bandwidth = true;
4513     params->has_max_cpu_throttle = true;
4514     params->has_announce_initial = true;
4515     params->has_announce_max = true;
4516     params->has_announce_rounds = true;
4517     params->has_announce_step = true;
4518 
4519     qemu_sem_init(&ms->postcopy_pause_sem, 0);
4520     qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
4521     qemu_sem_init(&ms->rp_state.rp_sem, 0);
4522     qemu_sem_init(&ms->rate_limit_sem, 0);
4523     qemu_sem_init(&ms->wait_unplug_sem, 0);
4524     qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
4525     qemu_mutex_init(&ms->qemu_file_lock);
4526 }
4527 
4528 /*
4529  * Return true if check pass, false otherwise. Error will be put
4530  * inside errp if provided.
4531  */
4532 static bool migration_object_check(MigrationState *ms, Error **errp)
4533 {
4534     MigrationCapabilityStatusList *head = NULL;
4535     /* Assuming all off */
4536     bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
4537     int i;
4538 
4539     if (!migrate_params_check(&ms->parameters, errp)) {
4540         return false;
4541     }
4542 
4543     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
4544         if (ms->enabled_capabilities[i]) {
4545             QAPI_LIST_PREPEND(head, migrate_cap_add(i, true));
4546         }
4547     }
4548 
4549     ret = migrate_caps_check(cap_list, head, errp);
4550 
4551     /* It works with head == NULL */
4552     qapi_free_MigrationCapabilityStatusList(head);
4553 
4554     return ret;
4555 }
4556 
4557 static const TypeInfo migration_type = {
4558     .name = TYPE_MIGRATION,
4559     /*
4560      * NOTE: TYPE_MIGRATION is not really a device, as the object is
4561      * not created using qdev_new(), it is not attached to the qdev
4562      * device tree, and it is never realized.
4563      *
4564      * TODO: Make this TYPE_OBJECT once QOM provides something like
4565      * TYPE_DEVICE's "-global" properties.
4566      */
4567     .parent = TYPE_DEVICE,
4568     .class_init = migration_class_init,
4569     .class_size = sizeof(MigrationClass),
4570     .instance_size = sizeof(MigrationState),
4571     .instance_init = migration_instance_init,
4572     .instance_finalize = migration_instance_finalize,
4573 };
4574 
4575 static void register_migration_types(void)
4576 {
4577     type_register_static(&migration_type);
4578 }
4579 
4580 type_init(register_migration_types);
4581