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