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