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