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