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