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