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