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