xref: /openbmc/qemu/migration/migration.c (revision b890902c9c025b87d02e718eec3090fd3525ab18)
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_use_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_use_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_use_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_use_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_use_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_use_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_use_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 bool migrate_use_multifd(void)
2562 {
2563     MigrationState *s;
2564 
2565     s = migrate_get_current();
2566 
2567     return s->capabilities[MIGRATION_CAPABILITY_MULTIFD];
2568 }
2569 
2570 int migrate_multifd_channels(void)
2571 {
2572     MigrationState *s;
2573 
2574     s = migrate_get_current();
2575 
2576     return s->parameters.multifd_channels;
2577 }
2578 
2579 MultiFDCompression migrate_multifd_compression(void)
2580 {
2581     MigrationState *s;
2582 
2583     s = migrate_get_current();
2584 
2585     assert(s->parameters.multifd_compression < MULTIFD_COMPRESSION__MAX);
2586     return s->parameters.multifd_compression;
2587 }
2588 
2589 int migrate_multifd_zlib_level(void)
2590 {
2591     MigrationState *s;
2592 
2593     s = migrate_get_current();
2594 
2595     return s->parameters.multifd_zlib_level;
2596 }
2597 
2598 int migrate_multifd_zstd_level(void)
2599 {
2600     MigrationState *s;
2601 
2602     s = migrate_get_current();
2603 
2604     return s->parameters.multifd_zstd_level;
2605 }
2606 
2607 #ifdef CONFIG_LINUX
2608 bool migrate_use_zero_copy_send(void)
2609 {
2610     MigrationState *s;
2611 
2612     s = migrate_get_current();
2613 
2614     return s->capabilities[MIGRATION_CAPABILITY_ZERO_COPY_SEND];
2615 }
2616 #endif
2617 
2618 int migrate_use_tls(void)
2619 {
2620     MigrationState *s;
2621 
2622     s = migrate_get_current();
2623 
2624     return s->parameters.tls_creds && *s->parameters.tls_creds;
2625 }
2626 
2627 int migrate_use_xbzrle(void)
2628 {
2629     MigrationState *s;
2630 
2631     s = migrate_get_current();
2632 
2633     return s->capabilities[MIGRATION_CAPABILITY_XBZRLE];
2634 }
2635 
2636 uint64_t migrate_xbzrle_cache_size(void)
2637 {
2638     MigrationState *s;
2639 
2640     s = migrate_get_current();
2641 
2642     return s->parameters.xbzrle_cache_size;
2643 }
2644 
2645 static int64_t migrate_max_postcopy_bandwidth(void)
2646 {
2647     MigrationState *s;
2648 
2649     s = migrate_get_current();
2650 
2651     return s->parameters.max_postcopy_bandwidth;
2652 }
2653 
2654 bool migrate_use_block(void)
2655 {
2656     MigrationState *s;
2657 
2658     s = migrate_get_current();
2659 
2660     return s->capabilities[MIGRATION_CAPABILITY_BLOCK];
2661 }
2662 
2663 bool migrate_use_return_path(void)
2664 {
2665     MigrationState *s;
2666 
2667     s = migrate_get_current();
2668 
2669     return s->capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2670 }
2671 
2672 bool migrate_use_block_incremental(void)
2673 {
2674     MigrationState *s;
2675 
2676     s = migrate_get_current();
2677 
2678     return s->parameters.block_incremental;
2679 }
2680 
2681 /* migration thread support */
2682 /*
2683  * Something bad happened to the RP stream, mark an error
2684  * The caller shall print or trace something to indicate why
2685  */
2686 static void mark_source_rp_bad(MigrationState *s)
2687 {
2688     s->rp_state.error = true;
2689 }
2690 
2691 static struct rp_cmd_args {
2692     ssize_t     len; /* -1 = variable */
2693     const char *name;
2694 } rp_cmd_args[] = {
2695     [MIG_RP_MSG_INVALID]        = { .len = -1, .name = "INVALID" },
2696     [MIG_RP_MSG_SHUT]           = { .len =  4, .name = "SHUT" },
2697     [MIG_RP_MSG_PONG]           = { .len =  4, .name = "PONG" },
2698     [MIG_RP_MSG_REQ_PAGES]      = { .len = 12, .name = "REQ_PAGES" },
2699     [MIG_RP_MSG_REQ_PAGES_ID]   = { .len = -1, .name = "REQ_PAGES_ID" },
2700     [MIG_RP_MSG_RECV_BITMAP]    = { .len = -1, .name = "RECV_BITMAP" },
2701     [MIG_RP_MSG_RESUME_ACK]     = { .len =  4, .name = "RESUME_ACK" },
2702     [MIG_RP_MSG_MAX]            = { .len = -1, .name = "MAX" },
2703 };
2704 
2705 /*
2706  * Process a request for pages received on the return path,
2707  * We're allowed to send more than requested (e.g. to round to our page size)
2708  * and we don't need to send pages that have already been sent.
2709  */
2710 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2711                                        ram_addr_t start, size_t len)
2712 {
2713     long our_host_ps = qemu_real_host_page_size();
2714 
2715     trace_migrate_handle_rp_req_pages(rbname, start, len);
2716 
2717     /*
2718      * Since we currently insist on matching page sizes, just sanity check
2719      * we're being asked for whole host pages.
2720      */
2721     if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
2722         !QEMU_IS_ALIGNED(len, our_host_ps)) {
2723         error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2724                      " len: %zd", __func__, start, len);
2725         mark_source_rp_bad(ms);
2726         return;
2727     }
2728 
2729     if (ram_save_queue_pages(rbname, start, len)) {
2730         mark_source_rp_bad(ms);
2731     }
2732 }
2733 
2734 /* Return true to retry, false to quit */
2735 static bool postcopy_pause_return_path_thread(MigrationState *s)
2736 {
2737     trace_postcopy_pause_return_path();
2738 
2739     qemu_sem_wait(&s->postcopy_pause_rp_sem);
2740 
2741     trace_postcopy_pause_return_path_continued();
2742 
2743     return true;
2744 }
2745 
2746 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2747 {
2748     RAMBlock *block = qemu_ram_block_by_name(block_name);
2749 
2750     if (!block) {
2751         error_report("%s: invalid block name '%s'", __func__, block_name);
2752         return -EINVAL;
2753     }
2754 
2755     /* Fetch the received bitmap and refresh the dirty bitmap */
2756     return ram_dirty_bitmap_reload(s, block);
2757 }
2758 
2759 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2760 {
2761     trace_source_return_path_thread_resume_ack(value);
2762 
2763     if (value != MIGRATION_RESUME_ACK_VALUE) {
2764         error_report("%s: illegal resume_ack value %"PRIu32,
2765                      __func__, value);
2766         return -1;
2767     }
2768 
2769     /* Now both sides are active. */
2770     migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2771                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2772 
2773     /* Notify send thread that time to continue send pages */
2774     qemu_sem_post(&s->rp_state.rp_sem);
2775 
2776     return 0;
2777 }
2778 
2779 /*
2780  * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2781  * existed) in a safe way.
2782  */
2783 static void migration_release_dst_files(MigrationState *ms)
2784 {
2785     QEMUFile *file;
2786 
2787     WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2788         /*
2789          * Reset the from_dst_file pointer first before releasing it, as we
2790          * can't block within lock section
2791          */
2792         file = ms->rp_state.from_dst_file;
2793         ms->rp_state.from_dst_file = NULL;
2794     }
2795 
2796     /*
2797      * Do the same to postcopy fast path socket too if there is.  No
2798      * locking needed because this qemufile should only be managed by
2799      * return path thread.
2800      */
2801     if (ms->postcopy_qemufile_src) {
2802         migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
2803         qemu_file_shutdown(ms->postcopy_qemufile_src);
2804         qemu_fclose(ms->postcopy_qemufile_src);
2805         ms->postcopy_qemufile_src = NULL;
2806     }
2807 
2808     qemu_fclose(file);
2809 }
2810 
2811 /*
2812  * Handles messages sent on the return path towards the source VM
2813  *
2814  */
2815 static void *source_return_path_thread(void *opaque)
2816 {
2817     MigrationState *ms = opaque;
2818     QEMUFile *rp = ms->rp_state.from_dst_file;
2819     uint16_t header_len, header_type;
2820     uint8_t buf[512];
2821     uint32_t tmp32, sibling_error;
2822     ram_addr_t start = 0; /* =0 to silence warning */
2823     size_t  len = 0, expected_len;
2824     int res;
2825 
2826     trace_source_return_path_thread_entry();
2827     rcu_register_thread();
2828 
2829 retry:
2830     while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2831            migration_is_setup_or_active(ms->state)) {
2832         trace_source_return_path_thread_loop_top();
2833         header_type = qemu_get_be16(rp);
2834         header_len = qemu_get_be16(rp);
2835 
2836         if (qemu_file_get_error(rp)) {
2837             mark_source_rp_bad(ms);
2838             goto out;
2839         }
2840 
2841         if (header_type >= MIG_RP_MSG_MAX ||
2842             header_type == MIG_RP_MSG_INVALID) {
2843             error_report("RP: Received invalid message 0x%04x length 0x%04x",
2844                          header_type, header_len);
2845             mark_source_rp_bad(ms);
2846             goto out;
2847         }
2848 
2849         if ((rp_cmd_args[header_type].len != -1 &&
2850             header_len != rp_cmd_args[header_type].len) ||
2851             header_len > sizeof(buf)) {
2852             error_report("RP: Received '%s' message (0x%04x) with"
2853                          "incorrect length %d expecting %zu",
2854                          rp_cmd_args[header_type].name, header_type, header_len,
2855                          (size_t)rp_cmd_args[header_type].len);
2856             mark_source_rp_bad(ms);
2857             goto out;
2858         }
2859 
2860         /* We know we've got a valid header by this point */
2861         res = qemu_get_buffer(rp, buf, header_len);
2862         if (res != header_len) {
2863             error_report("RP: Failed reading data for message 0x%04x"
2864                          " read %d expected %d",
2865                          header_type, res, header_len);
2866             mark_source_rp_bad(ms);
2867             goto out;
2868         }
2869 
2870         /* OK, we have the message and the data */
2871         switch (header_type) {
2872         case MIG_RP_MSG_SHUT:
2873             sibling_error = ldl_be_p(buf);
2874             trace_source_return_path_thread_shut(sibling_error);
2875             if (sibling_error) {
2876                 error_report("RP: Sibling indicated error %d", sibling_error);
2877                 mark_source_rp_bad(ms);
2878             }
2879             /*
2880              * We'll let the main thread deal with closing the RP
2881              * we could do a shutdown(2) on it, but we're the only user
2882              * anyway, so there's nothing gained.
2883              */
2884             goto out;
2885 
2886         case MIG_RP_MSG_PONG:
2887             tmp32 = ldl_be_p(buf);
2888             trace_source_return_path_thread_pong(tmp32);
2889             qemu_sem_post(&ms->rp_state.rp_pong_acks);
2890             break;
2891 
2892         case MIG_RP_MSG_REQ_PAGES:
2893             start = ldq_be_p(buf);
2894             len = ldl_be_p(buf + 8);
2895             migrate_handle_rp_req_pages(ms, NULL, start, len);
2896             break;
2897 
2898         case MIG_RP_MSG_REQ_PAGES_ID:
2899             expected_len = 12 + 1; /* header + termination */
2900 
2901             if (header_len >= expected_len) {
2902                 start = ldq_be_p(buf);
2903                 len = ldl_be_p(buf + 8);
2904                 /* Now we expect an idstr */
2905                 tmp32 = buf[12]; /* Length of the following idstr */
2906                 buf[13 + tmp32] = '\0';
2907                 expected_len += tmp32;
2908             }
2909             if (header_len != expected_len) {
2910                 error_report("RP: Req_Page_id with length %d expecting %zd",
2911                              header_len, expected_len);
2912                 mark_source_rp_bad(ms);
2913                 goto out;
2914             }
2915             migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2916             break;
2917 
2918         case MIG_RP_MSG_RECV_BITMAP:
2919             if (header_len < 1) {
2920                 error_report("%s: missing block name", __func__);
2921                 mark_source_rp_bad(ms);
2922                 goto out;
2923             }
2924             /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2925             buf[buf[0] + 1] = '\0';
2926             if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2927                 mark_source_rp_bad(ms);
2928                 goto out;
2929             }
2930             break;
2931 
2932         case MIG_RP_MSG_RESUME_ACK:
2933             tmp32 = ldl_be_p(buf);
2934             if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2935                 mark_source_rp_bad(ms);
2936                 goto out;
2937             }
2938             break;
2939 
2940         default:
2941             break;
2942         }
2943     }
2944 
2945 out:
2946     res = qemu_file_get_error(rp);
2947     if (res) {
2948         if (res && migration_in_postcopy()) {
2949             /*
2950              * Maybe there is something we can do: it looks like a
2951              * network down issue, and we pause for a recovery.
2952              */
2953             migration_release_dst_files(ms);
2954             rp = NULL;
2955             if (postcopy_pause_return_path_thread(ms)) {
2956                 /*
2957                  * Reload rp, reset the rest.  Referencing it is safe since
2958                  * it's reset only by us above, or when migration completes
2959                  */
2960                 rp = ms->rp_state.from_dst_file;
2961                 ms->rp_state.error = false;
2962                 goto retry;
2963             }
2964         }
2965 
2966         trace_source_return_path_thread_bad_end();
2967         mark_source_rp_bad(ms);
2968     }
2969 
2970     trace_source_return_path_thread_end();
2971     migration_release_dst_files(ms);
2972     rcu_unregister_thread();
2973     return NULL;
2974 }
2975 
2976 static int open_return_path_on_source(MigrationState *ms,
2977                                       bool create_thread)
2978 {
2979     ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2980     if (!ms->rp_state.from_dst_file) {
2981         return -1;
2982     }
2983 
2984     trace_open_return_path_on_source();
2985 
2986     if (!create_thread) {
2987         /* We're done */
2988         return 0;
2989     }
2990 
2991     qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2992                        source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2993     ms->rp_state.rp_thread_created = true;
2994 
2995     trace_open_return_path_on_source_continue();
2996 
2997     return 0;
2998 }
2999 
3000 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
3001 static int await_return_path_close_on_source(MigrationState *ms)
3002 {
3003     /*
3004      * If this is a normal exit then the destination will send a SHUT and the
3005      * rp_thread will exit, however if there's an error we need to cause
3006      * it to exit.
3007      */
3008     if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
3009         /*
3010          * shutdown(2), if we have it, will cause it to unblock if it's stuck
3011          * waiting for the destination.
3012          */
3013         qemu_file_shutdown(ms->rp_state.from_dst_file);
3014         mark_source_rp_bad(ms);
3015     }
3016     trace_await_return_path_close_on_source_joining();
3017     qemu_thread_join(&ms->rp_state.rp_thread);
3018     ms->rp_state.rp_thread_created = false;
3019     trace_await_return_path_close_on_source_close();
3020     return ms->rp_state.error;
3021 }
3022 
3023 static inline void
3024 migration_wait_main_channel(MigrationState *ms)
3025 {
3026     /* Wait until one PONG message received */
3027     qemu_sem_wait(&ms->rp_state.rp_pong_acks);
3028 }
3029 
3030 /*
3031  * Switch from normal iteration to postcopy
3032  * Returns non-0 on error
3033  */
3034 static int postcopy_start(MigrationState *ms)
3035 {
3036     int ret;
3037     QIOChannelBuffer *bioc;
3038     QEMUFile *fb;
3039     int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3040     int64_t bandwidth = migrate_max_postcopy_bandwidth();
3041     bool restart_block = false;
3042     int cur_state = MIGRATION_STATUS_ACTIVE;
3043 
3044     if (migrate_postcopy_preempt()) {
3045         migration_wait_main_channel(ms);
3046         if (postcopy_preempt_establish_channel(ms)) {
3047             migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
3048             return -1;
3049         }
3050     }
3051 
3052     if (!migrate_pause_before_switchover()) {
3053         migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
3054                           MIGRATION_STATUS_POSTCOPY_ACTIVE);
3055     }
3056 
3057     trace_postcopy_start();
3058     qemu_mutex_lock_iothread();
3059     trace_postcopy_start_set_run();
3060 
3061     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3062     global_state_store();
3063     ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
3064     if (ret < 0) {
3065         goto fail;
3066     }
3067 
3068     ret = migration_maybe_pause(ms, &cur_state,
3069                                 MIGRATION_STATUS_POSTCOPY_ACTIVE);
3070     if (ret < 0) {
3071         goto fail;
3072     }
3073 
3074     ret = bdrv_inactivate_all();
3075     if (ret < 0) {
3076         goto fail;
3077     }
3078     restart_block = true;
3079 
3080     /*
3081      * Cause any non-postcopiable, but iterative devices to
3082      * send out their final data.
3083      */
3084     qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
3085 
3086     /*
3087      * in Finish migrate and with the io-lock held everything should
3088      * be quiet, but we've potentially still got dirty pages and we
3089      * need to tell the destination to throw any pages it's already received
3090      * that are dirty
3091      */
3092     if (migrate_postcopy_ram()) {
3093         ram_postcopy_send_discard_bitmap(ms);
3094     }
3095 
3096     /*
3097      * send rest of state - note things that are doing postcopy
3098      * will notice we're in POSTCOPY_ACTIVE and not actually
3099      * wrap their state up here
3100      */
3101     /* 0 max-postcopy-bandwidth means unlimited */
3102     if (!bandwidth) {
3103         qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
3104     } else {
3105         qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
3106     }
3107     if (migrate_postcopy_ram()) {
3108         /* Ping just for debugging, helps line traces up */
3109         qemu_savevm_send_ping(ms->to_dst_file, 2);
3110     }
3111 
3112     /*
3113      * While loading the device state we may trigger page transfer
3114      * requests and the fd must be free to process those, and thus
3115      * the destination must read the whole device state off the fd before
3116      * it starts processing it.  Unfortunately the ad-hoc migration format
3117      * doesn't allow the destination to know the size to read without fully
3118      * parsing it through each devices load-state code (especially the open
3119      * coded devices that use get/put).
3120      * So we wrap the device state up in a package with a length at the start;
3121      * to do this we use a qemu_buf to hold the whole of the device state.
3122      */
3123     bioc = qio_channel_buffer_new(4096);
3124     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
3125     fb = qemu_file_new_output(QIO_CHANNEL(bioc));
3126     object_unref(OBJECT(bioc));
3127 
3128     /*
3129      * Make sure the receiver can get incoming pages before we send the rest
3130      * of the state
3131      */
3132     qemu_savevm_send_postcopy_listen(fb);
3133 
3134     qemu_savevm_state_complete_precopy(fb, false, false);
3135     if (migrate_postcopy_ram()) {
3136         qemu_savevm_send_ping(fb, 3);
3137     }
3138 
3139     qemu_savevm_send_postcopy_run(fb);
3140 
3141     /* <><> end of stuff going into the package */
3142 
3143     /* Last point of recovery; as soon as we send the package the destination
3144      * can open devices and potentially start running.
3145      * Lets just check again we've not got any errors.
3146      */
3147     ret = qemu_file_get_error(ms->to_dst_file);
3148     if (ret) {
3149         error_report("postcopy_start: Migration stream errored (pre package)");
3150         goto fail_closefb;
3151     }
3152 
3153     restart_block = false;
3154 
3155     /* Now send that blob */
3156     if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
3157         goto fail_closefb;
3158     }
3159     qemu_fclose(fb);
3160 
3161     /* Send a notify to give a chance for anything that needs to happen
3162      * at the transition to postcopy and after the device state; in particular
3163      * spice needs to trigger a transition now
3164      */
3165     ms->postcopy_after_devices = true;
3166     notifier_list_notify(&migration_state_notifiers, ms);
3167 
3168     ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
3169 
3170     qemu_mutex_unlock_iothread();
3171 
3172     if (migrate_postcopy_ram()) {
3173         /*
3174          * Although this ping is just for debug, it could potentially be
3175          * used for getting a better measurement of downtime at the source.
3176          */
3177         qemu_savevm_send_ping(ms->to_dst_file, 4);
3178     }
3179 
3180     if (migrate_release_ram()) {
3181         ram_postcopy_migrated_memory_release(ms);
3182     }
3183 
3184     ret = qemu_file_get_error(ms->to_dst_file);
3185     if (ret) {
3186         error_report("postcopy_start: Migration stream errored");
3187         migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
3188                               MIGRATION_STATUS_FAILED);
3189     }
3190 
3191     trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
3192 
3193     return ret;
3194 
3195 fail_closefb:
3196     qemu_fclose(fb);
3197 fail:
3198     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
3199                           MIGRATION_STATUS_FAILED);
3200     if (restart_block) {
3201         /* A failure happened early enough that we know the destination hasn't
3202          * accessed block devices, so we're safe to recover.
3203          */
3204         Error *local_err = NULL;
3205 
3206         bdrv_activate_all(&local_err);
3207         if (local_err) {
3208             error_report_err(local_err);
3209         }
3210     }
3211     qemu_mutex_unlock_iothread();
3212     return -1;
3213 }
3214 
3215 /**
3216  * migration_maybe_pause: Pause if required to by
3217  * migrate_pause_before_switchover called with the iothread locked
3218  * Returns: 0 on success
3219  */
3220 static int migration_maybe_pause(MigrationState *s,
3221                                  int *current_active_state,
3222                                  int new_state)
3223 {
3224     if (!migrate_pause_before_switchover()) {
3225         return 0;
3226     }
3227 
3228     /* Since leaving this state is not atomic with posting the semaphore
3229      * it's possible that someone could have issued multiple migrate_continue
3230      * and the semaphore is incorrectly positive at this point;
3231      * the docs say it's undefined to reinit a semaphore that's already
3232      * init'd, so use timedwait to eat up any existing posts.
3233      */
3234     while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
3235         /* This block intentionally left blank */
3236     }
3237 
3238     /*
3239      * If the migration is cancelled when it is in the completion phase,
3240      * the migration state is set to MIGRATION_STATUS_CANCELLING.
3241      * So we don't need to wait a semaphore, otherwise we would always
3242      * wait for the 'pause_sem' semaphore.
3243      */
3244     if (s->state != MIGRATION_STATUS_CANCELLING) {
3245         qemu_mutex_unlock_iothread();
3246         migrate_set_state(&s->state, *current_active_state,
3247                           MIGRATION_STATUS_PRE_SWITCHOVER);
3248         qemu_sem_wait(&s->pause_sem);
3249         migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
3250                           new_state);
3251         *current_active_state = new_state;
3252         qemu_mutex_lock_iothread();
3253     }
3254 
3255     return s->state == new_state ? 0 : -EINVAL;
3256 }
3257 
3258 /**
3259  * migration_completion: Used by migration_thread when there's not much left.
3260  *   The caller 'breaks' the loop when this returns.
3261  *
3262  * @s: Current migration state
3263  */
3264 static void migration_completion(MigrationState *s)
3265 {
3266     int ret;
3267     int current_active_state = s->state;
3268 
3269     if (s->state == MIGRATION_STATUS_ACTIVE) {
3270         qemu_mutex_lock_iothread();
3271         s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3272         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3273         s->vm_was_running = runstate_is_running();
3274         ret = global_state_store();
3275 
3276         if (!ret) {
3277             ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
3278             trace_migration_completion_vm_stop(ret);
3279             if (ret >= 0) {
3280                 ret = migration_maybe_pause(s, &current_active_state,
3281                                             MIGRATION_STATUS_DEVICE);
3282             }
3283             if (ret >= 0) {
3284                 s->block_inactive = !migrate_colo();
3285                 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
3286                 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
3287                                                          s->block_inactive);
3288             }
3289         }
3290         qemu_mutex_unlock_iothread();
3291 
3292         if (ret < 0) {
3293             goto fail;
3294         }
3295     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3296         trace_migration_completion_postcopy_end();
3297 
3298         qemu_mutex_lock_iothread();
3299         qemu_savevm_state_complete_postcopy(s->to_dst_file);
3300         qemu_mutex_unlock_iothread();
3301 
3302         /*
3303          * Shutdown the postcopy fast path thread.  This is only needed
3304          * when dest QEMU binary is old (7.1/7.2).  QEMU 8.0+ doesn't need
3305          * this.
3306          */
3307         if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
3308             postcopy_preempt_shutdown_file(s);
3309         }
3310 
3311         trace_migration_completion_postcopy_end_after_complete();
3312     } else {
3313         goto fail;
3314     }
3315 
3316     /*
3317      * If rp was opened we must clean up the thread before
3318      * cleaning everything else up (since if there are no failures
3319      * it will wait for the destination to send it's status in
3320      * a SHUT command).
3321      */
3322     if (s->rp_state.rp_thread_created) {
3323         int rp_error;
3324         trace_migration_return_path_end_before();
3325         rp_error = await_return_path_close_on_source(s);
3326         trace_migration_return_path_end_after(rp_error);
3327         if (rp_error) {
3328             goto fail_invalidate;
3329         }
3330     }
3331 
3332     if (qemu_file_get_error(s->to_dst_file)) {
3333         trace_migration_completion_file_err();
3334         goto fail_invalidate;
3335     }
3336 
3337     if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) {
3338         /* COLO does not support postcopy */
3339         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3340                           MIGRATION_STATUS_COLO);
3341     } else {
3342         migrate_set_state(&s->state, current_active_state,
3343                           MIGRATION_STATUS_COMPLETED);
3344     }
3345 
3346     return;
3347 
3348 fail_invalidate:
3349     /* If not doing postcopy, vm_start() will be called: let's regain
3350      * control on images.
3351      */
3352     if (s->state == MIGRATION_STATUS_ACTIVE ||
3353         s->state == MIGRATION_STATUS_DEVICE) {
3354         Error *local_err = NULL;
3355 
3356         qemu_mutex_lock_iothread();
3357         bdrv_activate_all(&local_err);
3358         if (local_err) {
3359             error_report_err(local_err);
3360             s->block_inactive = true;
3361         } else {
3362             s->block_inactive = false;
3363         }
3364         qemu_mutex_unlock_iothread();
3365     }
3366 
3367 fail:
3368     migrate_set_state(&s->state, current_active_state,
3369                       MIGRATION_STATUS_FAILED);
3370 }
3371 
3372 /**
3373  * bg_migration_completion: Used by bg_migration_thread when after all the
3374  *   RAM has been saved. The caller 'breaks' the loop when this returns.
3375  *
3376  * @s: Current migration state
3377  */
3378 static void bg_migration_completion(MigrationState *s)
3379 {
3380     int current_active_state = s->state;
3381 
3382     /*
3383      * Stop tracking RAM writes - un-protect memory, un-register UFFD
3384      * memory ranges, flush kernel wait queues and wake up threads
3385      * waiting for write fault to be resolved.
3386      */
3387     ram_write_tracking_stop();
3388 
3389     if (s->state == MIGRATION_STATUS_ACTIVE) {
3390         /*
3391          * By this moment we have RAM content saved into the migration stream.
3392          * The next step is to flush the non-RAM content (device state)
3393          * right after the ram content. The device state has been stored into
3394          * the temporary buffer before RAM saving started.
3395          */
3396         qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
3397         qemu_fflush(s->to_dst_file);
3398     } else if (s->state == MIGRATION_STATUS_CANCELLING) {
3399         goto fail;
3400     }
3401 
3402     if (qemu_file_get_error(s->to_dst_file)) {
3403         trace_migration_completion_file_err();
3404         goto fail;
3405     }
3406 
3407     migrate_set_state(&s->state, current_active_state,
3408                       MIGRATION_STATUS_COMPLETED);
3409     return;
3410 
3411 fail:
3412     migrate_set_state(&s->state, current_active_state,
3413                       MIGRATION_STATUS_FAILED);
3414 }
3415 
3416 typedef enum MigThrError {
3417     /* No error detected */
3418     MIG_THR_ERR_NONE = 0,
3419     /* Detected error, but resumed successfully */
3420     MIG_THR_ERR_RECOVERED = 1,
3421     /* Detected fatal error, need to exit */
3422     MIG_THR_ERR_FATAL = 2,
3423 } MigThrError;
3424 
3425 static int postcopy_resume_handshake(MigrationState *s)
3426 {
3427     qemu_savevm_send_postcopy_resume(s->to_dst_file);
3428 
3429     while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3430         qemu_sem_wait(&s->rp_state.rp_sem);
3431     }
3432 
3433     if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3434         return 0;
3435     }
3436 
3437     return -1;
3438 }
3439 
3440 /* Return zero if success, or <0 for error */
3441 static int postcopy_do_resume(MigrationState *s)
3442 {
3443     int ret;
3444 
3445     /*
3446      * Call all the resume_prepare() hooks, so that modules can be
3447      * ready for the migration resume.
3448      */
3449     ret = qemu_savevm_state_resume_prepare(s);
3450     if (ret) {
3451         error_report("%s: resume_prepare() failure detected: %d",
3452                      __func__, ret);
3453         return ret;
3454     }
3455 
3456     /*
3457      * If preempt is enabled, re-establish the preempt channel.  Note that
3458      * we do it after resume prepare to make sure the main channel will be
3459      * created before the preempt channel.  E.g. with weak network, the
3460      * dest QEMU may get messed up with the preempt and main channels on
3461      * the order of connection setup.  This guarantees the correct order.
3462      */
3463     ret = postcopy_preempt_establish_channel(s);
3464     if (ret) {
3465         error_report("%s: postcopy_preempt_establish_channel(): %d",
3466                      __func__, ret);
3467         return ret;
3468     }
3469 
3470     /*
3471      * Last handshake with destination on the resume (destination will
3472      * switch to postcopy-active afterwards)
3473      */
3474     ret = postcopy_resume_handshake(s);
3475     if (ret) {
3476         error_report("%s: handshake failed: %d", __func__, ret);
3477         return ret;
3478     }
3479 
3480     return 0;
3481 }
3482 
3483 /*
3484  * We don't return until we are in a safe state to continue current
3485  * postcopy migration.  Returns MIG_THR_ERR_RECOVERED if recovered, or
3486  * MIG_THR_ERR_FATAL if unrecovery failure happened.
3487  */
3488 static MigThrError postcopy_pause(MigrationState *s)
3489 {
3490     assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3491 
3492     while (true) {
3493         QEMUFile *file;
3494 
3495         /*
3496          * Current channel is possibly broken. Release it.  Note that this is
3497          * guaranteed even without lock because to_dst_file should only be
3498          * modified by the migration thread.  That also guarantees that the
3499          * unregister of yank is safe too without the lock.  It should be safe
3500          * even to be within the qemu_file_lock, but we didn't do that to avoid
3501          * taking more mutex (yank_lock) within qemu_file_lock.  TL;DR: we make
3502          * the qemu_file_lock critical section as small as possible.
3503          */
3504         assert(s->to_dst_file);
3505         migration_ioc_unregister_yank_from_file(s->to_dst_file);
3506         qemu_mutex_lock(&s->qemu_file_lock);
3507         file = s->to_dst_file;
3508         s->to_dst_file = NULL;
3509         qemu_mutex_unlock(&s->qemu_file_lock);
3510 
3511         qemu_file_shutdown(file);
3512         qemu_fclose(file);
3513 
3514         migrate_set_state(&s->state, s->state,
3515                           MIGRATION_STATUS_POSTCOPY_PAUSED);
3516 
3517         error_report("Detected IO failure for postcopy. "
3518                      "Migration paused.");
3519 
3520         /*
3521          * We wait until things fixed up. Then someone will setup the
3522          * status back for us.
3523          */
3524         while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3525             qemu_sem_wait(&s->postcopy_pause_sem);
3526         }
3527 
3528         if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3529             /* Woken up by a recover procedure. Give it a shot */
3530 
3531             /*
3532              * Firstly, let's wake up the return path now, with a new
3533              * return path channel.
3534              */
3535             qemu_sem_post(&s->postcopy_pause_rp_sem);
3536 
3537             /* Do the resume logic */
3538             if (postcopy_do_resume(s) == 0) {
3539                 /* Let's continue! */
3540                 trace_postcopy_pause_continued();
3541                 return MIG_THR_ERR_RECOVERED;
3542             } else {
3543                 /*
3544                  * Something wrong happened during the recovery, let's
3545                  * pause again. Pause is always better than throwing
3546                  * data away.
3547                  */
3548                 continue;
3549             }
3550         } else {
3551             /* This is not right... Time to quit. */
3552             return MIG_THR_ERR_FATAL;
3553         }
3554     }
3555 }
3556 
3557 static MigThrError migration_detect_error(MigrationState *s)
3558 {
3559     int ret;
3560     int state = s->state;
3561     Error *local_error = NULL;
3562 
3563     if (state == MIGRATION_STATUS_CANCELLING ||
3564         state == MIGRATION_STATUS_CANCELLED) {
3565         /* End the migration, but don't set the state to failed */
3566         return MIG_THR_ERR_FATAL;
3567     }
3568 
3569     /*
3570      * Try to detect any file errors.  Note that postcopy_qemufile_src will
3571      * be NULL when postcopy preempt is not enabled.
3572      */
3573     ret = qemu_file_get_error_obj_any(s->to_dst_file,
3574                                       s->postcopy_qemufile_src,
3575                                       &local_error);
3576     if (!ret) {
3577         /* Everything is fine */
3578         assert(!local_error);
3579         return MIG_THR_ERR_NONE;
3580     }
3581 
3582     if (local_error) {
3583         migrate_set_error(s, local_error);
3584         error_free(local_error);
3585     }
3586 
3587     if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
3588         /*
3589          * For postcopy, we allow the network to be down for a
3590          * while. After that, it can be continued by a
3591          * recovery phase.
3592          */
3593         return postcopy_pause(s);
3594     } else {
3595         /*
3596          * For precopy (or postcopy with error outside IO), we fail
3597          * with no time.
3598          */
3599         migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3600         trace_migration_thread_file_err();
3601 
3602         /* Time to stop the migration, now. */
3603         return MIG_THR_ERR_FATAL;
3604     }
3605 }
3606 
3607 /* How many bytes have we transferred since the beginning of the migration */
3608 static uint64_t migration_total_bytes(MigrationState *s)
3609 {
3610     return qemu_file_total_transferred(s->to_dst_file) +
3611         stat64_get(&ram_counters.multifd_bytes);
3612 }
3613 
3614 static void migration_calculate_complete(MigrationState *s)
3615 {
3616     uint64_t bytes = migration_total_bytes(s);
3617     int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3618     int64_t transfer_time;
3619 
3620     s->total_time = end_time - s->start_time;
3621     if (!s->downtime) {
3622         /*
3623          * It's still not set, so we are precopy migration.  For
3624          * postcopy, downtime is calculated during postcopy_start().
3625          */
3626         s->downtime = end_time - s->downtime_start;
3627     }
3628 
3629     transfer_time = s->total_time - s->setup_time;
3630     if (transfer_time) {
3631         s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3632     }
3633 }
3634 
3635 static void update_iteration_initial_status(MigrationState *s)
3636 {
3637     /*
3638      * Update these three fields at the same time to avoid mismatch info lead
3639      * wrong speed calculation.
3640      */
3641     s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3642     s->iteration_initial_bytes = migration_total_bytes(s);
3643     s->iteration_initial_pages = ram_get_total_transferred_pages();
3644 }
3645 
3646 static void migration_update_counters(MigrationState *s,
3647                                       int64_t current_time)
3648 {
3649     uint64_t transferred, transferred_pages, time_spent;
3650     uint64_t current_bytes; /* bytes transferred since the beginning */
3651     double bandwidth;
3652 
3653     if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3654         return;
3655     }
3656 
3657     current_bytes = migration_total_bytes(s);
3658     transferred = current_bytes - s->iteration_initial_bytes;
3659     time_spent = current_time - s->iteration_start_time;
3660     bandwidth = (double)transferred / time_spent;
3661     s->threshold_size = bandwidth * s->parameters.downtime_limit;
3662 
3663     s->mbps = (((double) transferred * 8.0) /
3664                ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3665 
3666     transferred_pages = ram_get_total_transferred_pages() -
3667                             s->iteration_initial_pages;
3668     s->pages_per_second = (double) transferred_pages /
3669                              (((double) time_spent / 1000.0));
3670 
3671     /*
3672      * if we haven't sent anything, we don't want to
3673      * recalculate. 10000 is a small enough number for our purposes
3674      */
3675     if (ram_counters.dirty_pages_rate && transferred > 10000) {
3676         s->expected_downtime = ram_counters.remaining / bandwidth;
3677     }
3678 
3679     qemu_file_reset_rate_limit(s->to_dst_file);
3680 
3681     update_iteration_initial_status(s);
3682 
3683     trace_migrate_transferred(transferred, time_spent,
3684                               bandwidth, s->threshold_size);
3685 }
3686 
3687 /* Migration thread iteration status */
3688 typedef enum {
3689     MIG_ITERATE_RESUME,         /* Resume current iteration */
3690     MIG_ITERATE_SKIP,           /* Skip current iteration */
3691     MIG_ITERATE_BREAK,          /* Break the loop */
3692 } MigIterateState;
3693 
3694 /*
3695  * Return true if continue to the next iteration directly, false
3696  * otherwise.
3697  */
3698 static MigIterateState migration_iteration_run(MigrationState *s)
3699 {
3700     uint64_t must_precopy, can_postcopy;
3701     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3702 
3703     qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
3704     uint64_t pending_size = must_precopy + can_postcopy;
3705 
3706     trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
3707 
3708     if (must_precopy <= s->threshold_size) {
3709         qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
3710         pending_size = must_precopy + can_postcopy;
3711         trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy);
3712     }
3713 
3714     if (!pending_size || pending_size < s->threshold_size) {
3715         trace_migration_thread_low_pending(pending_size);
3716         migration_completion(s);
3717         return MIG_ITERATE_BREAK;
3718     }
3719 
3720     /* Still a significant amount to transfer */
3721     if (!in_postcopy && must_precopy <= s->threshold_size &&
3722         qatomic_read(&s->start_postcopy)) {
3723         if (postcopy_start(s)) {
3724             error_report("%s: postcopy failed to start", __func__);
3725         }
3726         return MIG_ITERATE_SKIP;
3727     }
3728 
3729     /* Just another iteration step */
3730     qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3731     return MIG_ITERATE_RESUME;
3732 }
3733 
3734 static void migration_iteration_finish(MigrationState *s)
3735 {
3736     /* If we enabled cpu throttling for auto-converge, turn it off. */
3737     cpu_throttle_stop();
3738 
3739     qemu_mutex_lock_iothread();
3740     switch (s->state) {
3741     case MIGRATION_STATUS_COMPLETED:
3742         migration_calculate_complete(s);
3743         runstate_set(RUN_STATE_POSTMIGRATE);
3744         break;
3745     case MIGRATION_STATUS_COLO:
3746         if (!migrate_colo()) {
3747             error_report("%s: critical error: calling COLO code without "
3748                          "COLO enabled", __func__);
3749         }
3750         migrate_start_colo_process(s);
3751         s->vm_was_running = true;
3752         /* Fallthrough */
3753     case MIGRATION_STATUS_FAILED:
3754     case MIGRATION_STATUS_CANCELLED:
3755     case MIGRATION_STATUS_CANCELLING:
3756         if (s->vm_was_running) {
3757             if (!runstate_check(RUN_STATE_SHUTDOWN)) {
3758                 vm_start();
3759             }
3760         } else {
3761             if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3762                 runstate_set(RUN_STATE_POSTMIGRATE);
3763             }
3764         }
3765         break;
3766 
3767     default:
3768         /* Should not reach here, but if so, forgive the VM. */
3769         error_report("%s: Unknown ending state %d", __func__, s->state);
3770         break;
3771     }
3772     migrate_fd_cleanup_schedule(s);
3773     qemu_mutex_unlock_iothread();
3774 }
3775 
3776 static void bg_migration_iteration_finish(MigrationState *s)
3777 {
3778     qemu_mutex_lock_iothread();
3779     switch (s->state) {
3780     case MIGRATION_STATUS_COMPLETED:
3781         migration_calculate_complete(s);
3782         break;
3783 
3784     case MIGRATION_STATUS_ACTIVE:
3785     case MIGRATION_STATUS_FAILED:
3786     case MIGRATION_STATUS_CANCELLED:
3787     case MIGRATION_STATUS_CANCELLING:
3788         break;
3789 
3790     default:
3791         /* Should not reach here, but if so, forgive the VM. */
3792         error_report("%s: Unknown ending state %d", __func__, s->state);
3793         break;
3794     }
3795 
3796     migrate_fd_cleanup_schedule(s);
3797     qemu_mutex_unlock_iothread();
3798 }
3799 
3800 /*
3801  * Return true if continue to the next iteration directly, false
3802  * otherwise.
3803  */
3804 static MigIterateState bg_migration_iteration_run(MigrationState *s)
3805 {
3806     int res;
3807 
3808     res = qemu_savevm_state_iterate(s->to_dst_file, false);
3809     if (res > 0) {
3810         bg_migration_completion(s);
3811         return MIG_ITERATE_BREAK;
3812     }
3813 
3814     return MIG_ITERATE_RESUME;
3815 }
3816 
3817 void migration_make_urgent_request(void)
3818 {
3819     qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3820 }
3821 
3822 void migration_consume_urgent_request(void)
3823 {
3824     qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3825 }
3826 
3827 /* Returns true if the rate limiting was broken by an urgent request */
3828 bool migration_rate_limit(void)
3829 {
3830     int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3831     MigrationState *s = migrate_get_current();
3832 
3833     bool urgent = false;
3834     migration_update_counters(s, now);
3835     if (qemu_file_rate_limit(s->to_dst_file)) {
3836 
3837         if (qemu_file_get_error(s->to_dst_file)) {
3838             return false;
3839         }
3840         /*
3841          * Wait for a delay to do rate limiting OR
3842          * something urgent to post the semaphore.
3843          */
3844         int ms = s->iteration_start_time + BUFFER_DELAY - now;
3845         trace_migration_rate_limit_pre(ms);
3846         if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3847             /*
3848              * We were woken by one or more urgent things but
3849              * the timedwait will have consumed one of them.
3850              * The service routine for the urgent wake will dec
3851              * the semaphore itself for each item it consumes,
3852              * so add this one we just eat back.
3853              */
3854             qemu_sem_post(&s->rate_limit_sem);
3855             urgent = true;
3856         }
3857         trace_migration_rate_limit_post(urgent);
3858     }
3859     return urgent;
3860 }
3861 
3862 /*
3863  * if failover devices are present, wait they are completely
3864  * unplugged
3865  */
3866 
3867 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
3868                                     int new_state)
3869 {
3870     if (qemu_savevm_state_guest_unplug_pending()) {
3871         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
3872 
3873         while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3874                qemu_savevm_state_guest_unplug_pending()) {
3875             qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3876         }
3877         if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
3878             int timeout = 120; /* 30 seconds */
3879             /*
3880              * migration has been canceled
3881              * but as we have started an unplug we must wait the end
3882              * to be able to plug back the card
3883              */
3884             while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
3885                 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3886             }
3887             if (qemu_savevm_state_guest_unplug_pending() &&
3888                 !qtest_enabled()) {
3889                 warn_report("migration: partially unplugged device on "
3890                             "failure");
3891             }
3892         }
3893 
3894         migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
3895     } else {
3896         migrate_set_state(&s->state, old_state, new_state);
3897     }
3898 }
3899 
3900 /*
3901  * Master migration thread on the source VM.
3902  * It drives the migration and pumps the data down the outgoing channel.
3903  */
3904 static void *migration_thread(void *opaque)
3905 {
3906     MigrationState *s = opaque;
3907     MigrationThread *thread = NULL;
3908     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3909     MigThrError thr_error;
3910     bool urgent = false;
3911 
3912     thread = MigrationThreadAdd("live_migration", qemu_get_thread_id());
3913 
3914     rcu_register_thread();
3915 
3916     object_ref(OBJECT(s));
3917     update_iteration_initial_status(s);
3918 
3919     qemu_savevm_state_header(s->to_dst_file);
3920 
3921     /*
3922      * If we opened the return path, we need to make sure dst has it
3923      * opened as well.
3924      */
3925     if (s->rp_state.rp_thread_created) {
3926         /* Now tell the dest that it should open its end so it can reply */
3927         qemu_savevm_send_open_return_path(s->to_dst_file);
3928 
3929         /* And do a ping that will make stuff easier to debug */
3930         qemu_savevm_send_ping(s->to_dst_file, 1);
3931     }
3932 
3933     if (migrate_postcopy()) {
3934         /*
3935          * Tell the destination that we *might* want to do postcopy later;
3936          * if the other end can't do postcopy it should fail now, nice and
3937          * early.
3938          */
3939         qemu_savevm_send_postcopy_advise(s->to_dst_file);
3940     }
3941 
3942     if (migrate_colo()) {
3943         /* Notify migration destination that we enable COLO */
3944         qemu_savevm_send_colo_enable(s->to_dst_file);
3945     }
3946 
3947     qemu_savevm_state_setup(s->to_dst_file);
3948 
3949     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3950                                MIGRATION_STATUS_ACTIVE);
3951 
3952     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3953 
3954     trace_migration_thread_setup_complete();
3955 
3956     while (migration_is_active(s)) {
3957         if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3958             MigIterateState iter_state = migration_iteration_run(s);
3959             if (iter_state == MIG_ITERATE_SKIP) {
3960                 continue;
3961             } else if (iter_state == MIG_ITERATE_BREAK) {
3962                 break;
3963             }
3964         }
3965 
3966         /*
3967          * Try to detect any kind of failures, and see whether we
3968          * should stop the migration now.
3969          */
3970         thr_error = migration_detect_error(s);
3971         if (thr_error == MIG_THR_ERR_FATAL) {
3972             /* Stop migration */
3973             break;
3974         } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3975             /*
3976              * Just recovered from a e.g. network failure, reset all
3977              * the local variables. This is important to avoid
3978              * breaking transferred_bytes and bandwidth calculation
3979              */
3980             update_iteration_initial_status(s);
3981         }
3982 
3983         urgent = migration_rate_limit();
3984     }
3985 
3986     trace_migration_thread_after_loop();
3987     migration_iteration_finish(s);
3988     object_unref(OBJECT(s));
3989     rcu_unregister_thread();
3990     MigrationThreadDel(thread);
3991     return NULL;
3992 }
3993 
3994 static void bg_migration_vm_start_bh(void *opaque)
3995 {
3996     MigrationState *s = opaque;
3997 
3998     qemu_bh_delete(s->vm_start_bh);
3999     s->vm_start_bh = NULL;
4000 
4001     vm_start();
4002     s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
4003 }
4004 
4005 /**
4006  * Background snapshot thread, based on live migration code.
4007  * This is an alternative implementation of live migration mechanism
4008  * introduced specifically to support background snapshots.
4009  *
4010  * It takes advantage of userfault_fd write protection mechanism introduced
4011  * in v5.7 kernel. Compared to existing dirty page logging migration much
4012  * lesser stream traffic is produced resulting in smaller snapshot images,
4013  * simply cause of no page duplicates can get into the stream.
4014  *
4015  * Another key point is that generated vmstate stream reflects machine state
4016  * 'frozen' at the beginning of snapshot creation compared to dirty page logging
4017  * mechanism, which effectively results in that saved snapshot is the state of VM
4018  * at the end of the process.
4019  */
4020 static void *bg_migration_thread(void *opaque)
4021 {
4022     MigrationState *s = opaque;
4023     int64_t setup_start;
4024     MigThrError thr_error;
4025     QEMUFile *fb;
4026     bool early_fail = true;
4027 
4028     rcu_register_thread();
4029     object_ref(OBJECT(s));
4030 
4031     qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
4032 
4033     setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
4034     /*
4035      * We want to save vmstate for the moment when migration has been
4036      * initiated but also we want to save RAM content while VM is running.
4037      * The RAM content should appear first in the vmstate. So, we first
4038      * stash the non-RAM part of the vmstate to the temporary buffer,
4039      * then write RAM part of the vmstate to the migration stream
4040      * with vCPUs running and, finally, write stashed non-RAM part of
4041      * the vmstate from the buffer to the migration stream.
4042      */
4043     s->bioc = qio_channel_buffer_new(512 * 1024);
4044     qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
4045     fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
4046     object_unref(OBJECT(s->bioc));
4047 
4048     update_iteration_initial_status(s);
4049 
4050     /*
4051      * Prepare for tracking memory writes with UFFD-WP - populate
4052      * RAM pages before protecting.
4053      */
4054 #ifdef __linux__
4055     ram_write_tracking_prepare();
4056 #endif
4057 
4058     qemu_savevm_state_header(s->to_dst_file);
4059     qemu_savevm_state_setup(s->to_dst_file);
4060 
4061     qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
4062                                MIGRATION_STATUS_ACTIVE);
4063 
4064     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
4065 
4066     trace_migration_thread_setup_complete();
4067     s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
4068 
4069     qemu_mutex_lock_iothread();
4070 
4071     /*
4072      * If VM is currently in suspended state, then, to make a valid runstate
4073      * transition in vm_stop_force_state() we need to wakeup it up.
4074      */
4075     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
4076     s->vm_was_running = runstate_is_running();
4077 
4078     if (global_state_store()) {
4079         goto fail;
4080     }
4081     /* Forcibly stop VM before saving state of vCPUs and devices */
4082     if (vm_stop_force_state(RUN_STATE_PAUSED)) {
4083         goto fail;
4084     }
4085     /*
4086      * Put vCPUs in sync with shadow context structures, then
4087      * save their state to channel-buffer along with devices.
4088      */
4089     cpu_synchronize_all_states();
4090     if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
4091         goto fail;
4092     }
4093     /*
4094      * Since we are going to get non-iterable state data directly
4095      * from s->bioc->data, explicit flush is needed here.
4096      */
4097     qemu_fflush(fb);
4098 
4099     /* Now initialize UFFD context and start tracking RAM writes */
4100     if (ram_write_tracking_start()) {
4101         goto fail;
4102     }
4103     early_fail = false;
4104 
4105     /*
4106      * Start VM from BH handler to avoid write-fault lock here.
4107      * UFFD-WP protection for the whole RAM is already enabled so
4108      * calling VM state change notifiers from vm_start() would initiate
4109      * writes to virtio VQs memory which is in write-protected region.
4110      */
4111     s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
4112     qemu_bh_schedule(s->vm_start_bh);
4113 
4114     qemu_mutex_unlock_iothread();
4115 
4116     while (migration_is_active(s)) {
4117         MigIterateState iter_state = bg_migration_iteration_run(s);
4118         if (iter_state == MIG_ITERATE_SKIP) {
4119             continue;
4120         } else if (iter_state == MIG_ITERATE_BREAK) {
4121             break;
4122         }
4123 
4124         /*
4125          * Try to detect any kind of failures, and see whether we
4126          * should stop the migration now.
4127          */
4128         thr_error = migration_detect_error(s);
4129         if (thr_error == MIG_THR_ERR_FATAL) {
4130             /* Stop migration */
4131             break;
4132         }
4133 
4134         migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
4135     }
4136 
4137     trace_migration_thread_after_loop();
4138 
4139 fail:
4140     if (early_fail) {
4141         migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
4142                 MIGRATION_STATUS_FAILED);
4143         qemu_mutex_unlock_iothread();
4144     }
4145 
4146     bg_migration_iteration_finish(s);
4147 
4148     qemu_fclose(fb);
4149     object_unref(OBJECT(s));
4150     rcu_unregister_thread();
4151 
4152     return NULL;
4153 }
4154 
4155 void migrate_fd_connect(MigrationState *s, Error *error_in)
4156 {
4157     Error *local_err = NULL;
4158     int64_t rate_limit;
4159     bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
4160 
4161     /*
4162      * If there's a previous error, free it and prepare for another one.
4163      * Meanwhile if migration completes successfully, there won't have an error
4164      * dumped when calling migrate_fd_cleanup().
4165      */
4166     migrate_error_free(s);
4167 
4168     s->expected_downtime = s->parameters.downtime_limit;
4169     if (resume) {
4170         assert(s->cleanup_bh);
4171     } else {
4172         assert(!s->cleanup_bh);
4173         s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
4174     }
4175     if (error_in) {
4176         migrate_fd_error(s, error_in);
4177         if (resume) {
4178             /*
4179              * Don't do cleanup for resume if channel is invalid, but only dump
4180              * the error.  We wait for another channel connect from the user.
4181              * The error_report still gives HMP user a hint on what failed.
4182              * It's normally done in migrate_fd_cleanup(), but call it here
4183              * explicitly.
4184              */
4185             error_report_err(error_copy(s->error));
4186         } else {
4187             migrate_fd_cleanup(s);
4188         }
4189         return;
4190     }
4191 
4192     if (resume) {
4193         /* This is a resumed migration */
4194         rate_limit = s->parameters.max_postcopy_bandwidth /
4195             XFER_LIMIT_RATIO;
4196     } else {
4197         /* This is a fresh new migration */
4198         rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
4199 
4200         /* Notify before starting migration thread */
4201         notifier_list_notify(&migration_state_notifiers, s);
4202     }
4203 
4204     qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
4205     qemu_file_set_blocking(s->to_dst_file, true);
4206 
4207     /*
4208      * Open the return path. For postcopy, it is used exclusively. For
4209      * precopy, only if user specified "return-path" capability would
4210      * QEMU uses the return path.
4211      */
4212     if (migrate_postcopy_ram() || migrate_use_return_path()) {
4213         if (open_return_path_on_source(s, !resume)) {
4214             error_report("Unable to open return-path for postcopy");
4215             migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
4216             migrate_fd_cleanup(s);
4217             return;
4218         }
4219     }
4220 
4221     /*
4222      * This needs to be done before resuming a postcopy.  Note: for newer
4223      * QEMUs we will delay the channel creation until postcopy_start(), to
4224      * avoid disorder of channel creations.
4225      */
4226     if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
4227         postcopy_preempt_setup(s);
4228     }
4229 
4230     if (resume) {
4231         /* Wakeup the main migration thread to do the recovery */
4232         migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
4233                           MIGRATION_STATUS_POSTCOPY_RECOVER);
4234         qemu_sem_post(&s->postcopy_pause_sem);
4235         return;
4236     }
4237 
4238     if (multifd_save_setup(&local_err) != 0) {
4239         error_report_err(local_err);
4240         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4241                           MIGRATION_STATUS_FAILED);
4242         migrate_fd_cleanup(s);
4243         return;
4244     }
4245 
4246     if (migrate_background_snapshot()) {
4247         qemu_thread_create(&s->thread, "bg_snapshot",
4248                 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
4249     } else {
4250         qemu_thread_create(&s->thread, "live_migration",
4251                 migration_thread, s, QEMU_THREAD_JOINABLE);
4252     }
4253     s->migration_thread_running = true;
4254 }
4255 
4256 #define DEFINE_PROP_MIG_CAP(name, x)             \
4257     DEFINE_PROP_BOOL(name, MigrationState, capabilities[x], false)
4258 
4259 static Property migration_properties[] = {
4260     DEFINE_PROP_BOOL("store-global-state", MigrationState,
4261                      store_global_state, true),
4262     DEFINE_PROP_BOOL("send-configuration", MigrationState,
4263                      send_configuration, true),
4264     DEFINE_PROP_BOOL("send-section-footer", MigrationState,
4265                      send_section_footer, true),
4266     DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
4267                       decompress_error_check, true),
4268     DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
4269                       clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
4270     DEFINE_PROP_BOOL("x-preempt-pre-7-2", MigrationState,
4271                      preempt_pre_7_2, false),
4272 
4273     /* Migration parameters */
4274     DEFINE_PROP_UINT8("x-compress-level", MigrationState,
4275                       parameters.compress_level,
4276                       DEFAULT_MIGRATE_COMPRESS_LEVEL),
4277     DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
4278                       parameters.compress_threads,
4279                       DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
4280     DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
4281                       parameters.compress_wait_thread, true),
4282     DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
4283                       parameters.decompress_threads,
4284                       DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
4285     DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState,
4286                       parameters.throttle_trigger_threshold,
4287                       DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD),
4288     DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
4289                       parameters.cpu_throttle_initial,
4290                       DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
4291     DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
4292                       parameters.cpu_throttle_increment,
4293                       DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
4294     DEFINE_PROP_BOOL("x-cpu-throttle-tailslow", MigrationState,
4295                       parameters.cpu_throttle_tailslow, false),
4296     DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
4297                       parameters.max_bandwidth, MAX_THROTTLE),
4298     DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
4299                       parameters.downtime_limit,
4300                       DEFAULT_MIGRATE_SET_DOWNTIME),
4301     DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
4302                       parameters.x_checkpoint_delay,
4303                       DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
4304     DEFINE_PROP_UINT8("multifd-channels", MigrationState,
4305                       parameters.multifd_channels,
4306                       DEFAULT_MIGRATE_MULTIFD_CHANNELS),
4307     DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
4308                       parameters.multifd_compression,
4309                       DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
4310     DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
4311                       parameters.multifd_zlib_level,
4312                       DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
4313     DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
4314                       parameters.multifd_zstd_level,
4315                       DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
4316     DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
4317                       parameters.xbzrle_cache_size,
4318                       DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
4319     DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
4320                       parameters.max_postcopy_bandwidth,
4321                       DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
4322     DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
4323                       parameters.max_cpu_throttle,
4324                       DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
4325     DEFINE_PROP_SIZE("announce-initial", MigrationState,
4326                       parameters.announce_initial,
4327                       DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
4328     DEFINE_PROP_SIZE("announce-max", MigrationState,
4329                       parameters.announce_max,
4330                       DEFAULT_MIGRATE_ANNOUNCE_MAX),
4331     DEFINE_PROP_SIZE("announce-rounds", MigrationState,
4332                       parameters.announce_rounds,
4333                       DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
4334     DEFINE_PROP_SIZE("announce-step", MigrationState,
4335                       parameters.announce_step,
4336                       DEFAULT_MIGRATE_ANNOUNCE_STEP),
4337     DEFINE_PROP_STRING("tls-creds", MigrationState, parameters.tls_creds),
4338     DEFINE_PROP_STRING("tls-hostname", MigrationState, parameters.tls_hostname),
4339     DEFINE_PROP_STRING("tls-authz", MigrationState, parameters.tls_authz),
4340 
4341     /* Migration capabilities */
4342     DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
4343     DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
4344     DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
4345     DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
4346     DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
4347     DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
4348     DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
4349     DEFINE_PROP_MIG_CAP("x-postcopy-preempt",
4350                         MIGRATION_CAPABILITY_POSTCOPY_PREEMPT),
4351     DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
4352     DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
4353     DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
4354     DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
4355     DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
4356     DEFINE_PROP_MIG_CAP("x-background-snapshot",
4357             MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT),
4358 #ifdef CONFIG_LINUX
4359     DEFINE_PROP_MIG_CAP("x-zero-copy-send",
4360             MIGRATION_CAPABILITY_ZERO_COPY_SEND),
4361 #endif
4362 
4363     DEFINE_PROP_END_OF_LIST(),
4364 };
4365 
4366 static void migration_class_init(ObjectClass *klass, void *data)
4367 {
4368     DeviceClass *dc = DEVICE_CLASS(klass);
4369 
4370     dc->user_creatable = false;
4371     device_class_set_props(dc, migration_properties);
4372 }
4373 
4374 static void migration_instance_finalize(Object *obj)
4375 {
4376     MigrationState *ms = MIGRATION_OBJ(obj);
4377 
4378     qemu_mutex_destroy(&ms->error_mutex);
4379     qemu_mutex_destroy(&ms->qemu_file_lock);
4380     qemu_sem_destroy(&ms->wait_unplug_sem);
4381     qemu_sem_destroy(&ms->rate_limit_sem);
4382     qemu_sem_destroy(&ms->pause_sem);
4383     qemu_sem_destroy(&ms->postcopy_pause_sem);
4384     qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
4385     qemu_sem_destroy(&ms->rp_state.rp_sem);
4386     qemu_sem_destroy(&ms->rp_state.rp_pong_acks);
4387     qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
4388     error_free(ms->error);
4389 }
4390 
4391 static void migration_instance_init(Object *obj)
4392 {
4393     MigrationState *ms = MIGRATION_OBJ(obj);
4394     MigrationParameters *params = &ms->parameters;
4395 
4396     ms->state = MIGRATION_STATUS_NONE;
4397     ms->mbps = -1;
4398     ms->pages_per_second = -1;
4399     qemu_sem_init(&ms->pause_sem, 0);
4400     qemu_mutex_init(&ms->error_mutex);
4401 
4402     params->tls_hostname = g_strdup("");
4403     params->tls_creds = g_strdup("");
4404 
4405     /* Set has_* up only for parameter checks */
4406     params->has_compress_level = true;
4407     params->has_compress_threads = true;
4408     params->has_compress_wait_thread = true;
4409     params->has_decompress_threads = true;
4410     params->has_throttle_trigger_threshold = true;
4411     params->has_cpu_throttle_initial = true;
4412     params->has_cpu_throttle_increment = true;
4413     params->has_cpu_throttle_tailslow = true;
4414     params->has_max_bandwidth = true;
4415     params->has_downtime_limit = true;
4416     params->has_x_checkpoint_delay = true;
4417     params->has_block_incremental = true;
4418     params->has_multifd_channels = true;
4419     params->has_multifd_compression = true;
4420     params->has_multifd_zlib_level = true;
4421     params->has_multifd_zstd_level = true;
4422     params->has_xbzrle_cache_size = true;
4423     params->has_max_postcopy_bandwidth = true;
4424     params->has_max_cpu_throttle = true;
4425     params->has_announce_initial = true;
4426     params->has_announce_max = true;
4427     params->has_announce_rounds = true;
4428     params->has_announce_step = true;
4429 
4430     qemu_sem_init(&ms->postcopy_pause_sem, 0);
4431     qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
4432     qemu_sem_init(&ms->rp_state.rp_sem, 0);
4433     qemu_sem_init(&ms->rp_state.rp_pong_acks, 0);
4434     qemu_sem_init(&ms->rate_limit_sem, 0);
4435     qemu_sem_init(&ms->wait_unplug_sem, 0);
4436     qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
4437     qemu_mutex_init(&ms->qemu_file_lock);
4438 }
4439 
4440 /*
4441  * Return true if check pass, false otherwise. Error will be put
4442  * inside errp if provided.
4443  */
4444 static bool migration_object_check(MigrationState *ms, Error **errp)
4445 {
4446     /* Assuming all off */
4447     bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
4448 
4449     if (!migrate_params_check(&ms->parameters, errp)) {
4450         return false;
4451     }
4452 
4453     return migrate_caps_check(old_caps, ms->capabilities, errp);
4454 }
4455 
4456 static const TypeInfo migration_type = {
4457     .name = TYPE_MIGRATION,
4458     /*
4459      * NOTE: TYPE_MIGRATION is not really a device, as the object is
4460      * not created using qdev_new(), it is not attached to the qdev
4461      * device tree, and it is never realized.
4462      *
4463      * TODO: Make this TYPE_OBJECT once QOM provides something like
4464      * TYPE_DEVICE's "-global" properties.
4465      */
4466     .parent = TYPE_DEVICE,
4467     .class_init = migration_class_init,
4468     .class_size = sizeof(MigrationClass),
4469     .instance_size = sizeof(MigrationState),
4470     .instance_init = migration_instance_init,
4471     .instance_finalize = migration_instance_finalize,
4472 };
4473 
4474 static void register_migration_types(void)
4475 {
4476     type_register_static(&migration_type);
4477 }
4478 
4479 type_init(register_migration_types);
4480