xref: /openbmc/qemu/migration/migration.c (revision a2e2d7fc46fd8be875035d9bb5c64788389f65c2)
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 "migration/blocker.h"
20 #include "exec.h"
21 #include "fd.h"
22 #include "socket.h"
23 #include "rdma.h"
24 #include "ram.h"
25 #include "migration/global_state.h"
26 #include "migration/misc.h"
27 #include "migration.h"
28 #include "savevm.h"
29 #include "qemu-file-channel.h"
30 #include "qemu-file.h"
31 #include "migration/vmstate.h"
32 #include "block/block.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-commands-migration.h"
35 #include "qapi/qapi-events-migration.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qapi/qmp/qnull.h"
38 #include "qemu/rcu.h"
39 #include "block.h"
40 #include "postcopy-ram.h"
41 #include "qemu/thread.h"
42 #include "trace.h"
43 #include "exec/target_page.h"
44 #include "io/channel-buffer.h"
45 #include "migration/colo.h"
46 #include "hw/boards.h"
47 #include "monitor/monitor.h"
48 
49 #define MAX_THROTTLE  (32 << 20)      /* Migration transfer speed throttling */
50 
51 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
52  * data. */
53 #define BUFFER_DELAY     100
54 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
55 
56 /* Time in milliseconds we are allowed to stop the source,
57  * for sending the last part */
58 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
59 
60 /* Maximum migrate downtime set to 2000 seconds */
61 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
62 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
63 
64 /* Default compression thread count */
65 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
66 /* Default decompression thread count, usually decompression is at
67  * least 4 times as fast as compression.*/
68 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
69 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
70 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
71 /* Define default autoconverge cpu throttle migration parameters */
72 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
73 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
74 
75 /* Migration XBZRLE default cache size */
76 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
77 
78 /* The delay time (in ms) between two COLO checkpoints
79  * Note: Please change this default value to 10000 when we support hybrid mode.
80  */
81 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
82 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
83 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
84 
85 static NotifierList migration_state_notifiers =
86     NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
87 
88 static bool deferred_incoming;
89 
90 /* Messages sent on the return path from destination to source */
91 enum mig_rp_message_type {
92     MIG_RP_MSG_INVALID = 0,  /* Must be 0 */
93     MIG_RP_MSG_SHUT,         /* sibling will not send any more RP messages */
94     MIG_RP_MSG_PONG,         /* Response to a PING; data (seq: be32 ) */
95 
96     MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
97     MIG_RP_MSG_REQ_PAGES,    /* data (start: be64, len: be32) */
98 
99     MIG_RP_MSG_MAX
100 };
101 
102 /* When we add fault tolerance, we could have several
103    migrations at once.  For now we don't need to add
104    dynamic creation of migration */
105 
106 static MigrationState *current_migration;
107 
108 static bool migration_object_check(MigrationState *ms, Error **errp);
109 static int migration_maybe_pause(MigrationState *s,
110                                  int *current_active_state,
111                                  int new_state);
112 
113 void migration_object_init(void)
114 {
115     MachineState *ms = MACHINE(qdev_get_machine());
116     Error *err = NULL;
117 
118     /* This can only be called once. */
119     assert(!current_migration);
120     current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
121 
122     if (!migration_object_check(current_migration, &err)) {
123         error_report_err(err);
124         exit(1);
125     }
126 
127     /*
128      * We cannot really do this in migration_instance_init() since at
129      * that time global properties are not yet applied, then this
130      * value will be definitely replaced by something else.
131      */
132     if (ms->enforce_config_section) {
133         current_migration->send_configuration = true;
134     }
135 }
136 
137 void migration_object_finalize(void)
138 {
139     object_unref(OBJECT(current_migration));
140 }
141 
142 /* For outgoing */
143 MigrationState *migrate_get_current(void)
144 {
145     /* This can only be called after the object created. */
146     assert(current_migration);
147     return current_migration;
148 }
149 
150 MigrationIncomingState *migration_incoming_get_current(void)
151 {
152     static bool once;
153     static MigrationIncomingState mis_current;
154 
155     if (!once) {
156         mis_current.state = MIGRATION_STATUS_NONE;
157         memset(&mis_current, 0, sizeof(MigrationIncomingState));
158         mis_current.postcopy_remote_fds = g_array_new(FALSE, TRUE,
159                                                    sizeof(struct PostCopyFD));
160         qemu_mutex_init(&mis_current.rp_mutex);
161         qemu_event_init(&mis_current.main_thread_load_event, false);
162 
163         init_dirty_bitmap_incoming_migration();
164 
165         once = true;
166     }
167     return &mis_current;
168 }
169 
170 void migration_incoming_state_destroy(void)
171 {
172     struct MigrationIncomingState *mis = migration_incoming_get_current();
173 
174     if (mis->to_src_file) {
175         /* Tell source that we are done */
176         migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
177         qemu_fclose(mis->to_src_file);
178         mis->to_src_file = NULL;
179     }
180 
181     if (mis->from_src_file) {
182         qemu_fclose(mis->from_src_file);
183         mis->from_src_file = NULL;
184     }
185     if (mis->postcopy_remote_fds) {
186         g_array_free(mis->postcopy_remote_fds, TRUE);
187         mis->postcopy_remote_fds = NULL;
188     }
189 
190     qemu_event_reset(&mis->main_thread_load_event);
191 }
192 
193 static void migrate_generate_event(int new_state)
194 {
195     if (migrate_use_events()) {
196         qapi_event_send_migration(new_state, &error_abort);
197     }
198 }
199 
200 /*
201  * Called on -incoming with a defer: uri.
202  * The migration can be started later after any parameters have been
203  * changed.
204  */
205 static void deferred_incoming_migration(Error **errp)
206 {
207     if (deferred_incoming) {
208         error_setg(errp, "Incoming migration already deferred");
209     }
210     deferred_incoming = true;
211 }
212 
213 /*
214  * Send a message on the return channel back to the source
215  * of the migration.
216  */
217 static int migrate_send_rp_message(MigrationIncomingState *mis,
218                                    enum mig_rp_message_type message_type,
219                                    uint16_t len, void *data)
220 {
221     int ret = 0;
222 
223     trace_migrate_send_rp_message((int)message_type, len);
224     qemu_mutex_lock(&mis->rp_mutex);
225 
226     /*
227      * It's possible that the file handle got lost due to network
228      * failures.
229      */
230     if (!mis->to_src_file) {
231         ret = -EIO;
232         goto error;
233     }
234 
235     qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
236     qemu_put_be16(mis->to_src_file, len);
237     qemu_put_buffer(mis->to_src_file, data, len);
238     qemu_fflush(mis->to_src_file);
239 
240     /* It's possible that qemu file got error during sending */
241     ret = qemu_file_get_error(mis->to_src_file);
242 
243 error:
244     qemu_mutex_unlock(&mis->rp_mutex);
245     return ret;
246 }
247 
248 /* Request a range of pages from the source VM at the given
249  * start address.
250  *   rbname: Name of the RAMBlock to request the page in, if NULL it's the same
251  *           as the last request (a name must have been given previously)
252  *   Start: Address offset within the RB
253  *   Len: Length in bytes required - must be a multiple of pagesize
254  */
255 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
256                               ram_addr_t start, size_t len)
257 {
258     uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
259     size_t msglen = 12; /* start + len */
260     enum mig_rp_message_type msg_type;
261 
262     *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
263     *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
264 
265     if (rbname) {
266         int rbname_len = strlen(rbname);
267         assert(rbname_len < 256);
268 
269         bufc[msglen++] = rbname_len;
270         memcpy(bufc + msglen, rbname, rbname_len);
271         msglen += rbname_len;
272         msg_type = MIG_RP_MSG_REQ_PAGES_ID;
273     } else {
274         msg_type = MIG_RP_MSG_REQ_PAGES;
275     }
276 
277     return migrate_send_rp_message(mis, msg_type, msglen, bufc);
278 }
279 
280 void qemu_start_incoming_migration(const char *uri, Error **errp)
281 {
282     const char *p;
283 
284     qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
285     if (!strcmp(uri, "defer")) {
286         deferred_incoming_migration(errp);
287     } else if (strstart(uri, "tcp:", &p)) {
288         tcp_start_incoming_migration(p, errp);
289 #ifdef CONFIG_RDMA
290     } else if (strstart(uri, "rdma:", &p)) {
291         rdma_start_incoming_migration(p, errp);
292 #endif
293     } else if (strstart(uri, "exec:", &p)) {
294         exec_start_incoming_migration(p, errp);
295     } else if (strstart(uri, "unix:", &p)) {
296         unix_start_incoming_migration(p, errp);
297     } else if (strstart(uri, "fd:", &p)) {
298         fd_start_incoming_migration(p, errp);
299     } else {
300         error_setg(errp, "unknown migration protocol: %s", uri);
301     }
302 }
303 
304 static void process_incoming_migration_bh(void *opaque)
305 {
306     Error *local_err = NULL;
307     MigrationIncomingState *mis = opaque;
308 
309     /* Make sure all file formats flush their mutable metadata.
310      * If we get an error here, just don't restart the VM yet. */
311     bdrv_invalidate_cache_all(&local_err);
312     if (local_err) {
313         error_report_err(local_err);
314         local_err = NULL;
315         autostart = false;
316     }
317 
318     /*
319      * This must happen after all error conditions are dealt with and
320      * we're sure the VM is going to be running on this host.
321      */
322     qemu_announce_self();
323 
324     if (multifd_load_cleanup(&local_err) != 0) {
325         error_report_err(local_err);
326         autostart = false;
327     }
328     /* If global state section was not received or we are in running
329        state, we need to obey autostart. Any other state is set with
330        runstate_set. */
331 
332     dirty_bitmap_mig_before_vm_start();
333 
334     if (!global_state_received() ||
335         global_state_get_runstate() == RUN_STATE_RUNNING) {
336         if (autostart) {
337             vm_start();
338         } else {
339             runstate_set(RUN_STATE_PAUSED);
340         }
341     } else {
342         runstate_set(global_state_get_runstate());
343     }
344     /*
345      * This must happen after any state changes since as soon as an external
346      * observer sees this event they might start to prod at the VM assuming
347      * it's ready to use.
348      */
349     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
350                       MIGRATION_STATUS_COMPLETED);
351     qemu_bh_delete(mis->bh);
352     migration_incoming_state_destroy();
353 }
354 
355 static void process_incoming_migration_co(void *opaque)
356 {
357     MigrationIncomingState *mis = migration_incoming_get_current();
358     PostcopyState ps;
359     int ret;
360 
361     assert(mis->from_src_file);
362     mis->largest_page_size = qemu_ram_pagesize_largest();
363     postcopy_state_set(POSTCOPY_INCOMING_NONE);
364     migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
365                       MIGRATION_STATUS_ACTIVE);
366     ret = qemu_loadvm_state(mis->from_src_file);
367 
368     ps = postcopy_state_get();
369     trace_process_incoming_migration_co_end(ret, ps);
370     if (ps != POSTCOPY_INCOMING_NONE) {
371         if (ps == POSTCOPY_INCOMING_ADVISE) {
372             /*
373              * Where a migration had postcopy enabled (and thus went to advise)
374              * but managed to complete within the precopy period, we can use
375              * the normal exit.
376              */
377             postcopy_ram_incoming_cleanup(mis);
378         } else if (ret >= 0) {
379             /*
380              * Postcopy was started, cleanup should happen at the end of the
381              * postcopy thread.
382              */
383             trace_process_incoming_migration_co_postcopy_end_main();
384             return;
385         }
386         /* Else if something went wrong then just fall out of the normal exit */
387     }
388 
389     /* we get COLO info, and know if we are in COLO mode */
390     if (!ret && migration_incoming_enable_colo()) {
391         mis->migration_incoming_co = qemu_coroutine_self();
392         qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
393              colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
394         mis->have_colo_incoming_thread = true;
395         qemu_coroutine_yield();
396 
397         /* Wait checkpoint incoming thread exit before free resource */
398         qemu_thread_join(&mis->colo_incoming_thread);
399     }
400 
401     if (ret < 0) {
402         Error *local_err = NULL;
403 
404         migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
405                           MIGRATION_STATUS_FAILED);
406         error_report("load of migration failed: %s", strerror(-ret));
407         qemu_fclose(mis->from_src_file);
408         if (multifd_load_cleanup(&local_err) != 0) {
409             error_report_err(local_err);
410         }
411         exit(EXIT_FAILURE);
412     }
413     mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
414     qemu_bh_schedule(mis->bh);
415 }
416 
417 static void migration_incoming_setup(QEMUFile *f)
418 {
419     MigrationIncomingState *mis = migration_incoming_get_current();
420 
421     if (multifd_load_setup() != 0) {
422         /* We haven't been able to create multifd threads
423            nothing better to do */
424         exit(EXIT_FAILURE);
425     }
426 
427     if (!mis->from_src_file) {
428         mis->from_src_file = f;
429     }
430     qemu_file_set_blocking(f, false);
431 }
432 
433 static void migration_incoming_process(void)
434 {
435     Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
436     qemu_coroutine_enter(co);
437 }
438 
439 void migration_fd_process_incoming(QEMUFile *f)
440 {
441     migration_incoming_setup(f);
442     migration_incoming_process();
443 }
444 
445 void migration_ioc_process_incoming(QIOChannel *ioc)
446 {
447     MigrationIncomingState *mis = migration_incoming_get_current();
448 
449     if (!mis->from_src_file) {
450         QEMUFile *f = qemu_fopen_channel_input(ioc);
451         migration_fd_process_incoming(f);
452     }
453     /* We still only have a single channel.  Nothing to do here yet */
454 }
455 
456 /**
457  * @migration_has_all_channels: We have received all channels that we need
458  *
459  * Returns true when we have got connections to all the channels that
460  * we need for migration.
461  */
462 bool migration_has_all_channels(void)
463 {
464     return true;
465 }
466 
467 /*
468  * Send a 'SHUT' message on the return channel with the given value
469  * to indicate that we've finished with the RP.  Non-0 value indicates
470  * error.
471  */
472 void migrate_send_rp_shut(MigrationIncomingState *mis,
473                           uint32_t value)
474 {
475     uint32_t buf;
476 
477     buf = cpu_to_be32(value);
478     migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
479 }
480 
481 /*
482  * Send a 'PONG' message on the return channel with the given value
483  * (normally in response to a 'PING')
484  */
485 void migrate_send_rp_pong(MigrationIncomingState *mis,
486                           uint32_t value)
487 {
488     uint32_t buf;
489 
490     buf = cpu_to_be32(value);
491     migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
492 }
493 
494 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
495 {
496     MigrationCapabilityStatusList *head = NULL;
497     MigrationCapabilityStatusList *caps;
498     MigrationState *s = migrate_get_current();
499     int i;
500 
501     caps = NULL; /* silence compiler warning */
502     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
503 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
504         if (i == MIGRATION_CAPABILITY_BLOCK) {
505             continue;
506         }
507 #endif
508         if (head == NULL) {
509             head = g_malloc0(sizeof(*caps));
510             caps = head;
511         } else {
512             caps->next = g_malloc0(sizeof(*caps));
513             caps = caps->next;
514         }
515         caps->value =
516             g_malloc(sizeof(*caps->value));
517         caps->value->capability = i;
518         caps->value->state = s->enabled_capabilities[i];
519     }
520 
521     return head;
522 }
523 
524 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
525 {
526     MigrationParameters *params;
527     MigrationState *s = migrate_get_current();
528 
529     /* TODO use QAPI_CLONE() instead of duplicating it inline */
530     params = g_malloc0(sizeof(*params));
531     params->has_compress_level = true;
532     params->compress_level = s->parameters.compress_level;
533     params->has_compress_threads = true;
534     params->compress_threads = s->parameters.compress_threads;
535     params->has_decompress_threads = true;
536     params->decompress_threads = s->parameters.decompress_threads;
537     params->has_cpu_throttle_initial = true;
538     params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
539     params->has_cpu_throttle_increment = true;
540     params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
541     params->has_tls_creds = true;
542     params->tls_creds = g_strdup(s->parameters.tls_creds);
543     params->has_tls_hostname = true;
544     params->tls_hostname = g_strdup(s->parameters.tls_hostname);
545     params->has_max_bandwidth = true;
546     params->max_bandwidth = s->parameters.max_bandwidth;
547     params->has_downtime_limit = true;
548     params->downtime_limit = s->parameters.downtime_limit;
549     params->has_x_checkpoint_delay = true;
550     params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
551     params->has_block_incremental = true;
552     params->block_incremental = s->parameters.block_incremental;
553     params->has_x_multifd_channels = true;
554     params->x_multifd_channels = s->parameters.x_multifd_channels;
555     params->has_x_multifd_page_count = true;
556     params->x_multifd_page_count = s->parameters.x_multifd_page_count;
557     params->has_xbzrle_cache_size = true;
558     params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
559 
560     return params;
561 }
562 
563 /*
564  * Return true if we're already in the middle of a migration
565  * (i.e. any of the active or setup states)
566  */
567 static bool migration_is_setup_or_active(int state)
568 {
569     switch (state) {
570     case MIGRATION_STATUS_ACTIVE:
571     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
572     case MIGRATION_STATUS_SETUP:
573     case MIGRATION_STATUS_PRE_SWITCHOVER:
574     case MIGRATION_STATUS_DEVICE:
575         return true;
576 
577     default:
578         return false;
579 
580     }
581 }
582 
583 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
584 {
585     info->has_ram = true;
586     info->ram = g_malloc0(sizeof(*info->ram));
587     info->ram->transferred = ram_counters.transferred;
588     info->ram->total = ram_bytes_total();
589     info->ram->duplicate = ram_counters.duplicate;
590     /* legacy value.  It is not used anymore */
591     info->ram->skipped = 0;
592     info->ram->normal = ram_counters.normal;
593     info->ram->normal_bytes = ram_counters.normal *
594         qemu_target_page_size();
595     info->ram->mbps = s->mbps;
596     info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
597     info->ram->postcopy_requests = ram_counters.postcopy_requests;
598     info->ram->page_size = qemu_target_page_size();
599 
600     if (migrate_use_xbzrle()) {
601         info->has_xbzrle_cache = true;
602         info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
603         info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
604         info->xbzrle_cache->bytes = xbzrle_counters.bytes;
605         info->xbzrle_cache->pages = xbzrle_counters.pages;
606         info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
607         info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
608         info->xbzrle_cache->overflow = xbzrle_counters.overflow;
609     }
610 
611     if (cpu_throttle_active()) {
612         info->has_cpu_throttle_percentage = true;
613         info->cpu_throttle_percentage = cpu_throttle_get_percentage();
614     }
615 
616     if (s->state != MIGRATION_STATUS_COMPLETED) {
617         info->ram->remaining = ram_bytes_remaining();
618         info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
619     }
620 }
621 
622 static void populate_disk_info(MigrationInfo *info)
623 {
624     if (blk_mig_active()) {
625         info->has_disk = true;
626         info->disk = g_malloc0(sizeof(*info->disk));
627         info->disk->transferred = blk_mig_bytes_transferred();
628         info->disk->remaining = blk_mig_bytes_remaining();
629         info->disk->total = blk_mig_bytes_total();
630     }
631 }
632 
633 MigrationInfo *qmp_query_migrate(Error **errp)
634 {
635     MigrationInfo *info = g_malloc0(sizeof(*info));
636     MigrationState *s = migrate_get_current();
637 
638     switch (s->state) {
639     case MIGRATION_STATUS_NONE:
640         /* no migration has happened ever */
641         break;
642     case MIGRATION_STATUS_SETUP:
643         info->has_status = true;
644         info->has_total_time = false;
645         break;
646     case MIGRATION_STATUS_ACTIVE:
647     case MIGRATION_STATUS_CANCELLING:
648     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
649     case MIGRATION_STATUS_PRE_SWITCHOVER:
650     case MIGRATION_STATUS_DEVICE:
651          /* TODO add some postcopy stats */
652         info->has_status = true;
653         info->has_total_time = true;
654         info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
655             - s->start_time;
656         info->has_expected_downtime = true;
657         info->expected_downtime = s->expected_downtime;
658         info->has_setup_time = true;
659         info->setup_time = s->setup_time;
660 
661         populate_ram_info(info, s);
662         populate_disk_info(info);
663         break;
664     case MIGRATION_STATUS_COLO:
665         info->has_status = true;
666         /* TODO: display COLO specific information (checkpoint info etc.) */
667         break;
668     case MIGRATION_STATUS_COMPLETED:
669         info->has_status = true;
670         info->has_total_time = true;
671         info->total_time = s->total_time;
672         info->has_downtime = true;
673         info->downtime = s->downtime;
674         info->has_setup_time = true;
675         info->setup_time = s->setup_time;
676 
677         populate_ram_info(info, s);
678         break;
679     case MIGRATION_STATUS_FAILED:
680         info->has_status = true;
681         if (s->error) {
682             info->has_error_desc = true;
683             info->error_desc = g_strdup(error_get_pretty(s->error));
684         }
685         break;
686     case MIGRATION_STATUS_CANCELLED:
687         info->has_status = true;
688         break;
689     }
690     info->status = s->state;
691 
692     return info;
693 }
694 
695 /**
696  * @migration_caps_check - check capability validity
697  *
698  * @cap_list: old capability list, array of bool
699  * @params: new capabilities to be applied soon
700  * @errp: set *errp if the check failed, with reason
701  *
702  * Returns true if check passed, otherwise false.
703  */
704 static bool migrate_caps_check(bool *cap_list,
705                                MigrationCapabilityStatusList *params,
706                                Error **errp)
707 {
708     MigrationCapabilityStatusList *cap;
709     bool old_postcopy_cap;
710     MigrationIncomingState *mis = migration_incoming_get_current();
711 
712     old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
713 
714     for (cap = params; cap; cap = cap->next) {
715         cap_list[cap->value->capability] = cap->value->state;
716     }
717 
718 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
719     if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
720         error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
721                    "block migration");
722         error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
723         return false;
724     }
725 #endif
726 
727     if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
728         if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
729             /* The decompression threads asynchronously write into RAM
730              * rather than use the atomic copies needed to avoid
731              * userfaulting.  It should be possible to fix the decompression
732              * threads for compatibility in future.
733              */
734             error_setg(errp, "Postcopy is not currently compatible "
735                        "with compression");
736             return false;
737         }
738 
739         /* This check is reasonably expensive, so only when it's being
740          * set the first time, also it's only the destination that needs
741          * special support.
742          */
743         if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
744             !postcopy_ram_supported_by_host(mis)) {
745             /* postcopy_ram_supported_by_host will have emitted a more
746              * detailed message
747              */
748             error_setg(errp, "Postcopy is not supported");
749             return false;
750         }
751     }
752 
753     return true;
754 }
755 
756 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
757                                   Error **errp)
758 {
759     MigrationState *s = migrate_get_current();
760     MigrationCapabilityStatusList *cap;
761     bool cap_list[MIGRATION_CAPABILITY__MAX];
762 
763     if (migration_is_setup_or_active(s->state)) {
764         error_setg(errp, QERR_MIGRATION_ACTIVE);
765         return;
766     }
767 
768     memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
769     if (!migrate_caps_check(cap_list, params, errp)) {
770         return;
771     }
772 
773     for (cap = params; cap; cap = cap->next) {
774         s->enabled_capabilities[cap->value->capability] = cap->value->state;
775     }
776 }
777 
778 /*
779  * Check whether the parameters are valid. Error will be put into errp
780  * (if provided). Return true if valid, otherwise false.
781  */
782 static bool migrate_params_check(MigrationParameters *params, Error **errp)
783 {
784     if (params->has_compress_level &&
785         (params->compress_level > 9)) {
786         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
787                    "is invalid, it should be in the range of 0 to 9");
788         return false;
789     }
790 
791     if (params->has_compress_threads && (params->compress_threads < 1)) {
792         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
793                    "compress_threads",
794                    "is invalid, it should be in the range of 1 to 255");
795         return false;
796     }
797 
798     if (params->has_decompress_threads && (params->decompress_threads < 1)) {
799         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
800                    "decompress_threads",
801                    "is invalid, it should be in the range of 1 to 255");
802         return false;
803     }
804 
805     if (params->has_cpu_throttle_initial &&
806         (params->cpu_throttle_initial < 1 ||
807          params->cpu_throttle_initial > 99)) {
808         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
809                    "cpu_throttle_initial",
810                    "an integer in the range of 1 to 99");
811         return false;
812     }
813 
814     if (params->has_cpu_throttle_increment &&
815         (params->cpu_throttle_increment < 1 ||
816          params->cpu_throttle_increment > 99)) {
817         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
818                    "cpu_throttle_increment",
819                    "an integer in the range of 1 to 99");
820         return false;
821     }
822 
823     if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
824         error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
825                          " range of 0 to %zu bytes/second", SIZE_MAX);
826         return false;
827     }
828 
829     if (params->has_downtime_limit &&
830         (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
831         error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
832                          "the range of 0 to %d milliseconds",
833                          MAX_MIGRATE_DOWNTIME);
834         return false;
835     }
836 
837     /* x_checkpoint_delay is now always positive */
838 
839     if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
840         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
841                    "multifd_channels",
842                    "is invalid, it should be in the range of 1 to 255");
843         return false;
844     }
845     if (params->has_x_multifd_page_count &&
846         (params->x_multifd_page_count < 1 ||
847          params->x_multifd_page_count > 10000)) {
848         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
849                    "multifd_page_count",
850                    "is invalid, it should be in the range of 1 to 10000");
851         return false;
852     }
853 
854     if (params->has_xbzrle_cache_size &&
855         (params->xbzrle_cache_size < qemu_target_page_size() ||
856          !is_power_of_2(params->xbzrle_cache_size))) {
857         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
858                    "xbzrle_cache_size",
859                    "is invalid, it should be bigger than target page size"
860                    " and a power of two");
861         return false;
862     }
863 
864     return true;
865 }
866 
867 static void migrate_params_test_apply(MigrateSetParameters *params,
868                                       MigrationParameters *dest)
869 {
870     *dest = migrate_get_current()->parameters;
871 
872     /* TODO use QAPI_CLONE() instead of duplicating it inline */
873 
874     if (params->has_compress_level) {
875         dest->compress_level = params->compress_level;
876     }
877 
878     if (params->has_compress_threads) {
879         dest->compress_threads = params->compress_threads;
880     }
881 
882     if (params->has_decompress_threads) {
883         dest->decompress_threads = params->decompress_threads;
884     }
885 
886     if (params->has_cpu_throttle_initial) {
887         dest->cpu_throttle_initial = params->cpu_throttle_initial;
888     }
889 
890     if (params->has_cpu_throttle_increment) {
891         dest->cpu_throttle_increment = params->cpu_throttle_increment;
892     }
893 
894     if (params->has_tls_creds) {
895         assert(params->tls_creds->type == QTYPE_QSTRING);
896         dest->tls_creds = g_strdup(params->tls_creds->u.s);
897     }
898 
899     if (params->has_tls_hostname) {
900         assert(params->tls_hostname->type == QTYPE_QSTRING);
901         dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
902     }
903 
904     if (params->has_max_bandwidth) {
905         dest->max_bandwidth = params->max_bandwidth;
906     }
907 
908     if (params->has_downtime_limit) {
909         dest->downtime_limit = params->downtime_limit;
910     }
911 
912     if (params->has_x_checkpoint_delay) {
913         dest->x_checkpoint_delay = params->x_checkpoint_delay;
914     }
915 
916     if (params->has_block_incremental) {
917         dest->block_incremental = params->block_incremental;
918     }
919     if (params->has_x_multifd_channels) {
920         dest->x_multifd_channels = params->x_multifd_channels;
921     }
922     if (params->has_x_multifd_page_count) {
923         dest->x_multifd_page_count = params->x_multifd_page_count;
924     }
925     if (params->has_xbzrle_cache_size) {
926         dest->xbzrle_cache_size = params->xbzrle_cache_size;
927     }
928 }
929 
930 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
931 {
932     MigrationState *s = migrate_get_current();
933 
934     /* TODO use QAPI_CLONE() instead of duplicating it inline */
935 
936     if (params->has_compress_level) {
937         s->parameters.compress_level = params->compress_level;
938     }
939 
940     if (params->has_compress_threads) {
941         s->parameters.compress_threads = params->compress_threads;
942     }
943 
944     if (params->has_decompress_threads) {
945         s->parameters.decompress_threads = params->decompress_threads;
946     }
947 
948     if (params->has_cpu_throttle_initial) {
949         s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
950     }
951 
952     if (params->has_cpu_throttle_increment) {
953         s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
954     }
955 
956     if (params->has_tls_creds) {
957         g_free(s->parameters.tls_creds);
958         assert(params->tls_creds->type == QTYPE_QSTRING);
959         s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
960     }
961 
962     if (params->has_tls_hostname) {
963         g_free(s->parameters.tls_hostname);
964         assert(params->tls_hostname->type == QTYPE_QSTRING);
965         s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
966     }
967 
968     if (params->has_max_bandwidth) {
969         s->parameters.max_bandwidth = params->max_bandwidth;
970         if (s->to_dst_file) {
971             qemu_file_set_rate_limit(s->to_dst_file,
972                                 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
973         }
974     }
975 
976     if (params->has_downtime_limit) {
977         s->parameters.downtime_limit = params->downtime_limit;
978     }
979 
980     if (params->has_x_checkpoint_delay) {
981         s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
982         if (migration_in_colo_state()) {
983             colo_checkpoint_notify(s);
984         }
985     }
986 
987     if (params->has_block_incremental) {
988         s->parameters.block_incremental = params->block_incremental;
989     }
990     if (params->has_x_multifd_channels) {
991         s->parameters.x_multifd_channels = params->x_multifd_channels;
992     }
993     if (params->has_x_multifd_page_count) {
994         s->parameters.x_multifd_page_count = params->x_multifd_page_count;
995     }
996     if (params->has_xbzrle_cache_size) {
997         s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
998         xbzrle_cache_resize(params->xbzrle_cache_size, errp);
999     }
1000 }
1001 
1002 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1003 {
1004     MigrationParameters tmp;
1005 
1006     /* TODO Rewrite "" to null instead */
1007     if (params->has_tls_creds
1008         && params->tls_creds->type == QTYPE_QNULL) {
1009         QDECREF(params->tls_creds->u.n);
1010         params->tls_creds->type = QTYPE_QSTRING;
1011         params->tls_creds->u.s = strdup("");
1012     }
1013     /* TODO Rewrite "" to null instead */
1014     if (params->has_tls_hostname
1015         && params->tls_hostname->type == QTYPE_QNULL) {
1016         QDECREF(params->tls_hostname->u.n);
1017         params->tls_hostname->type = QTYPE_QSTRING;
1018         params->tls_hostname->u.s = strdup("");
1019     }
1020 
1021     migrate_params_test_apply(params, &tmp);
1022 
1023     if (!migrate_params_check(&tmp, errp)) {
1024         /* Invalid parameter */
1025         return;
1026     }
1027 
1028     migrate_params_apply(params, errp);
1029 }
1030 
1031 
1032 void qmp_migrate_start_postcopy(Error **errp)
1033 {
1034     MigrationState *s = migrate_get_current();
1035 
1036     if (!migrate_postcopy()) {
1037         error_setg(errp, "Enable postcopy with migrate_set_capability before"
1038                          " the start of migration");
1039         return;
1040     }
1041 
1042     if (s->state == MIGRATION_STATUS_NONE) {
1043         error_setg(errp, "Postcopy must be started after migration has been"
1044                          " started");
1045         return;
1046     }
1047     /*
1048      * we don't error if migration has finished since that would be racy
1049      * with issuing this command.
1050      */
1051     atomic_set(&s->start_postcopy, true);
1052 }
1053 
1054 /* shared migration helpers */
1055 
1056 void migrate_set_state(int *state, int old_state, int new_state)
1057 {
1058     assert(new_state < MIGRATION_STATUS__MAX);
1059     if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1060         trace_migrate_set_state(MigrationStatus_str(new_state));
1061         migrate_generate_event(new_state);
1062     }
1063 }
1064 
1065 static MigrationCapabilityStatusList *migrate_cap_add(
1066     MigrationCapabilityStatusList *list,
1067     MigrationCapability index,
1068     bool state)
1069 {
1070     MigrationCapabilityStatusList *cap;
1071 
1072     cap = g_new0(MigrationCapabilityStatusList, 1);
1073     cap->value = g_new0(MigrationCapabilityStatus, 1);
1074     cap->value->capability = index;
1075     cap->value->state = state;
1076     cap->next = list;
1077 
1078     return cap;
1079 }
1080 
1081 void migrate_set_block_enabled(bool value, Error **errp)
1082 {
1083     MigrationCapabilityStatusList *cap;
1084 
1085     cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1086     qmp_migrate_set_capabilities(cap, errp);
1087     qapi_free_MigrationCapabilityStatusList(cap);
1088 }
1089 
1090 static void migrate_set_block_incremental(MigrationState *s, bool value)
1091 {
1092     s->parameters.block_incremental = value;
1093 }
1094 
1095 static void block_cleanup_parameters(MigrationState *s)
1096 {
1097     if (s->must_remove_block_options) {
1098         /* setting to false can never fail */
1099         migrate_set_block_enabled(false, &error_abort);
1100         migrate_set_block_incremental(s, false);
1101         s->must_remove_block_options = false;
1102     }
1103 }
1104 
1105 static void migrate_fd_cleanup(void *opaque)
1106 {
1107     MigrationState *s = opaque;
1108 
1109     qemu_bh_delete(s->cleanup_bh);
1110     s->cleanup_bh = NULL;
1111 
1112     qemu_savevm_state_cleanup();
1113 
1114     if (s->to_dst_file) {
1115         Error *local_err = NULL;
1116 
1117         trace_migrate_fd_cleanup();
1118         qemu_mutex_unlock_iothread();
1119         if (s->migration_thread_running) {
1120             qemu_thread_join(&s->thread);
1121             s->migration_thread_running = false;
1122         }
1123         qemu_mutex_lock_iothread();
1124 
1125         if (multifd_save_cleanup(&local_err) != 0) {
1126             error_report_err(local_err);
1127         }
1128         qemu_fclose(s->to_dst_file);
1129         s->to_dst_file = NULL;
1130     }
1131 
1132     assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1133            (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
1134 
1135     if (s->state == MIGRATION_STATUS_CANCELLING) {
1136         migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1137                           MIGRATION_STATUS_CANCELLED);
1138     }
1139 
1140     if (s->error) {
1141         /* It is used on info migrate.  We can't free it */
1142         error_report_err(error_copy(s->error));
1143     }
1144     notifier_list_notify(&migration_state_notifiers, s);
1145     block_cleanup_parameters(s);
1146 }
1147 
1148 void migrate_set_error(MigrationState *s, const Error *error)
1149 {
1150     qemu_mutex_lock(&s->error_mutex);
1151     if (!s->error) {
1152         s->error = error_copy(error);
1153     }
1154     qemu_mutex_unlock(&s->error_mutex);
1155 }
1156 
1157 void migrate_fd_error(MigrationState *s, const Error *error)
1158 {
1159     trace_migrate_fd_error(error_get_pretty(error));
1160     assert(s->to_dst_file == NULL);
1161     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1162                       MIGRATION_STATUS_FAILED);
1163     migrate_set_error(s, error);
1164 }
1165 
1166 static void migrate_fd_cancel(MigrationState *s)
1167 {
1168     int old_state ;
1169     QEMUFile *f = migrate_get_current()->to_dst_file;
1170     trace_migrate_fd_cancel();
1171 
1172     if (s->rp_state.from_dst_file) {
1173         /* shutdown the rp socket, so causing the rp thread to shutdown */
1174         qemu_file_shutdown(s->rp_state.from_dst_file);
1175     }
1176 
1177     do {
1178         old_state = s->state;
1179         if (!migration_is_setup_or_active(old_state)) {
1180             break;
1181         }
1182         /* If the migration is paused, kick it out of the pause */
1183         if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1184             qemu_sem_post(&s->pause_sem);
1185         }
1186         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1187     } while (s->state != MIGRATION_STATUS_CANCELLING);
1188 
1189     /*
1190      * If we're unlucky the migration code might be stuck somewhere in a
1191      * send/write while the network has failed and is waiting to timeout;
1192      * if we've got shutdown(2) available then we can force it to quit.
1193      * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1194      * called in a bh, so there is no race against this cancel.
1195      */
1196     if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1197         qemu_file_shutdown(f);
1198     }
1199     if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1200         Error *local_err = NULL;
1201 
1202         bdrv_invalidate_cache_all(&local_err);
1203         if (local_err) {
1204             error_report_err(local_err);
1205         } else {
1206             s->block_inactive = false;
1207         }
1208     }
1209 }
1210 
1211 void add_migration_state_change_notifier(Notifier *notify)
1212 {
1213     notifier_list_add(&migration_state_notifiers, notify);
1214 }
1215 
1216 void remove_migration_state_change_notifier(Notifier *notify)
1217 {
1218     notifier_remove(notify);
1219 }
1220 
1221 bool migration_in_setup(MigrationState *s)
1222 {
1223     return s->state == MIGRATION_STATUS_SETUP;
1224 }
1225 
1226 bool migration_has_finished(MigrationState *s)
1227 {
1228     return s->state == MIGRATION_STATUS_COMPLETED;
1229 }
1230 
1231 bool migration_has_failed(MigrationState *s)
1232 {
1233     return (s->state == MIGRATION_STATUS_CANCELLED ||
1234             s->state == MIGRATION_STATUS_FAILED);
1235 }
1236 
1237 bool migration_in_postcopy(void)
1238 {
1239     MigrationState *s = migrate_get_current();
1240 
1241     return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1242 }
1243 
1244 bool migration_in_postcopy_after_devices(MigrationState *s)
1245 {
1246     return migration_in_postcopy() && s->postcopy_after_devices;
1247 }
1248 
1249 bool migration_is_idle(void)
1250 {
1251     MigrationState *s = migrate_get_current();
1252 
1253     switch (s->state) {
1254     case MIGRATION_STATUS_NONE:
1255     case MIGRATION_STATUS_CANCELLED:
1256     case MIGRATION_STATUS_COMPLETED:
1257     case MIGRATION_STATUS_FAILED:
1258         return true;
1259     case MIGRATION_STATUS_SETUP:
1260     case MIGRATION_STATUS_CANCELLING:
1261     case MIGRATION_STATUS_ACTIVE:
1262     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1263     case MIGRATION_STATUS_COLO:
1264     case MIGRATION_STATUS_PRE_SWITCHOVER:
1265     case MIGRATION_STATUS_DEVICE:
1266         return false;
1267     case MIGRATION_STATUS__MAX:
1268         g_assert_not_reached();
1269     }
1270 
1271     return false;
1272 }
1273 
1274 void migrate_init(MigrationState *s)
1275 {
1276     /*
1277      * Reinitialise all migration state, except
1278      * parameters/capabilities that the user set, and
1279      * locks.
1280      */
1281     s->bytes_xfer = 0;
1282     s->xfer_limit = 0;
1283     s->cleanup_bh = 0;
1284     s->to_dst_file = NULL;
1285     s->state = MIGRATION_STATUS_NONE;
1286     s->rp_state.from_dst_file = NULL;
1287     s->rp_state.error = false;
1288     s->mbps = 0.0;
1289     s->downtime = 0;
1290     s->expected_downtime = 0;
1291     s->setup_time = 0;
1292     s->start_postcopy = false;
1293     s->postcopy_after_devices = false;
1294     s->migration_thread_running = false;
1295     error_free(s->error);
1296     s->error = NULL;
1297 
1298     migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1299 
1300     s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1301     s->total_time = 0;
1302     s->vm_was_running = false;
1303     s->iteration_initial_bytes = 0;
1304     s->threshold_size = 0;
1305 }
1306 
1307 static GSList *migration_blockers;
1308 
1309 int migrate_add_blocker(Error *reason, Error **errp)
1310 {
1311     if (migrate_get_current()->only_migratable) {
1312         error_propagate(errp, error_copy(reason));
1313         error_prepend(errp, "disallowing migration blocker "
1314                           "(--only_migratable) for: ");
1315         return -EACCES;
1316     }
1317 
1318     if (migration_is_idle()) {
1319         migration_blockers = g_slist_prepend(migration_blockers, reason);
1320         return 0;
1321     }
1322 
1323     error_propagate(errp, error_copy(reason));
1324     error_prepend(errp, "disallowing migration blocker (migration in "
1325                       "progress) for: ");
1326     return -EBUSY;
1327 }
1328 
1329 void migrate_del_blocker(Error *reason)
1330 {
1331     migration_blockers = g_slist_remove(migration_blockers, reason);
1332 }
1333 
1334 void qmp_migrate_incoming(const char *uri, Error **errp)
1335 {
1336     Error *local_err = NULL;
1337     static bool once = true;
1338 
1339     if (!deferred_incoming) {
1340         error_setg(errp, "For use with '-incoming defer'");
1341         return;
1342     }
1343     if (!once) {
1344         error_setg(errp, "The incoming migration has already been started");
1345     }
1346 
1347     qemu_start_incoming_migration(uri, &local_err);
1348 
1349     if (local_err) {
1350         error_propagate(errp, local_err);
1351         return;
1352     }
1353 
1354     once = false;
1355 }
1356 
1357 bool migration_is_blocked(Error **errp)
1358 {
1359     if (qemu_savevm_state_blocked(errp)) {
1360         return true;
1361     }
1362 
1363     if (migration_blockers) {
1364         error_propagate(errp, error_copy(migration_blockers->data));
1365         return true;
1366     }
1367 
1368     return false;
1369 }
1370 
1371 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1372                  bool has_inc, bool inc, bool has_detach, bool detach,
1373                  Error **errp)
1374 {
1375     Error *local_err = NULL;
1376     MigrationState *s = migrate_get_current();
1377     const char *p;
1378 
1379     if (migration_is_setup_or_active(s->state) ||
1380         s->state == MIGRATION_STATUS_CANCELLING ||
1381         s->state == MIGRATION_STATUS_COLO) {
1382         error_setg(errp, QERR_MIGRATION_ACTIVE);
1383         return;
1384     }
1385     if (runstate_check(RUN_STATE_INMIGRATE)) {
1386         error_setg(errp, "Guest is waiting for an incoming migration");
1387         return;
1388     }
1389 
1390     if (migration_is_blocked(errp)) {
1391         return;
1392     }
1393 
1394     if ((has_blk && blk) || (has_inc && inc)) {
1395         if (migrate_use_block() || migrate_use_block_incremental()) {
1396             error_setg(errp, "Command options are incompatible with "
1397                        "current migration capabilities");
1398             return;
1399         }
1400         migrate_set_block_enabled(true, &local_err);
1401         if (local_err) {
1402             error_propagate(errp, local_err);
1403             return;
1404         }
1405         s->must_remove_block_options = true;
1406     }
1407 
1408     if (has_inc && inc) {
1409         migrate_set_block_incremental(s, true);
1410     }
1411 
1412     migrate_init(s);
1413 
1414     if (strstart(uri, "tcp:", &p)) {
1415         tcp_start_outgoing_migration(s, p, &local_err);
1416 #ifdef CONFIG_RDMA
1417     } else if (strstart(uri, "rdma:", &p)) {
1418         rdma_start_outgoing_migration(s, p, &local_err);
1419 #endif
1420     } else if (strstart(uri, "exec:", &p)) {
1421         exec_start_outgoing_migration(s, p, &local_err);
1422     } else if (strstart(uri, "unix:", &p)) {
1423         unix_start_outgoing_migration(s, p, &local_err);
1424     } else if (strstart(uri, "fd:", &p)) {
1425         fd_start_outgoing_migration(s, p, &local_err);
1426     } else {
1427         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1428                    "a valid migration protocol");
1429         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1430                           MIGRATION_STATUS_FAILED);
1431         return;
1432     }
1433 
1434     if (local_err) {
1435         migrate_fd_error(s, local_err);
1436         error_propagate(errp, local_err);
1437         return;
1438     }
1439 }
1440 
1441 void qmp_migrate_cancel(Error **errp)
1442 {
1443     migrate_fd_cancel(migrate_get_current());
1444 }
1445 
1446 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1447 {
1448     MigrationState *s = migrate_get_current();
1449     if (s->state != state) {
1450         error_setg(errp,  "Migration not in expected state: %s",
1451                    MigrationStatus_str(s->state));
1452         return;
1453     }
1454     qemu_sem_post(&s->pause_sem);
1455 }
1456 
1457 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1458 {
1459     MigrateSetParameters p = {
1460         .has_xbzrle_cache_size = true,
1461         .xbzrle_cache_size = value,
1462     };
1463 
1464     qmp_migrate_set_parameters(&p, errp);
1465 }
1466 
1467 int64_t qmp_query_migrate_cache_size(Error **errp)
1468 {
1469     return migrate_xbzrle_cache_size();
1470 }
1471 
1472 void qmp_migrate_set_speed(int64_t value, Error **errp)
1473 {
1474     MigrateSetParameters p = {
1475         .has_max_bandwidth = true,
1476         .max_bandwidth = value,
1477     };
1478 
1479     qmp_migrate_set_parameters(&p, errp);
1480 }
1481 
1482 void qmp_migrate_set_downtime(double value, Error **errp)
1483 {
1484     if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1485         error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1486                          "the range of 0 to %d seconds",
1487                          MAX_MIGRATE_DOWNTIME_SECONDS);
1488         return;
1489     }
1490 
1491     value *= 1000; /* Convert to milliseconds */
1492     value = MAX(0, MIN(INT64_MAX, value));
1493 
1494     MigrateSetParameters p = {
1495         .has_downtime_limit = true,
1496         .downtime_limit = value,
1497     };
1498 
1499     qmp_migrate_set_parameters(&p, errp);
1500 }
1501 
1502 bool migrate_release_ram(void)
1503 {
1504     MigrationState *s;
1505 
1506     s = migrate_get_current();
1507 
1508     return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1509 }
1510 
1511 bool migrate_postcopy_ram(void)
1512 {
1513     MigrationState *s;
1514 
1515     s = migrate_get_current();
1516 
1517     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1518 }
1519 
1520 bool migrate_postcopy(void)
1521 {
1522     return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1523 }
1524 
1525 bool migrate_auto_converge(void)
1526 {
1527     MigrationState *s;
1528 
1529     s = migrate_get_current();
1530 
1531     return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1532 }
1533 
1534 bool migrate_zero_blocks(void)
1535 {
1536     MigrationState *s;
1537 
1538     s = migrate_get_current();
1539 
1540     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1541 }
1542 
1543 bool migrate_use_compression(void)
1544 {
1545     MigrationState *s;
1546 
1547     s = migrate_get_current();
1548 
1549     return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1550 }
1551 
1552 int migrate_compress_level(void)
1553 {
1554     MigrationState *s;
1555 
1556     s = migrate_get_current();
1557 
1558     return s->parameters.compress_level;
1559 }
1560 
1561 int migrate_compress_threads(void)
1562 {
1563     MigrationState *s;
1564 
1565     s = migrate_get_current();
1566 
1567     return s->parameters.compress_threads;
1568 }
1569 
1570 int migrate_decompress_threads(void)
1571 {
1572     MigrationState *s;
1573 
1574     s = migrate_get_current();
1575 
1576     return s->parameters.decompress_threads;
1577 }
1578 
1579 bool migrate_dirty_bitmaps(void)
1580 {
1581     MigrationState *s;
1582 
1583     s = migrate_get_current();
1584 
1585     return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1586 }
1587 
1588 bool migrate_use_events(void)
1589 {
1590     MigrationState *s;
1591 
1592     s = migrate_get_current();
1593 
1594     return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1595 }
1596 
1597 bool migrate_use_multifd(void)
1598 {
1599     MigrationState *s;
1600 
1601     s = migrate_get_current();
1602 
1603     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1604 }
1605 
1606 bool migrate_pause_before_switchover(void)
1607 {
1608     MigrationState *s;
1609 
1610     s = migrate_get_current();
1611 
1612     return s->enabled_capabilities[
1613         MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1614 }
1615 
1616 int migrate_multifd_channels(void)
1617 {
1618     MigrationState *s;
1619 
1620     s = migrate_get_current();
1621 
1622     return s->parameters.x_multifd_channels;
1623 }
1624 
1625 int migrate_multifd_page_count(void)
1626 {
1627     MigrationState *s;
1628 
1629     s = migrate_get_current();
1630 
1631     return s->parameters.x_multifd_page_count;
1632 }
1633 
1634 int migrate_use_xbzrle(void)
1635 {
1636     MigrationState *s;
1637 
1638     s = migrate_get_current();
1639 
1640     return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1641 }
1642 
1643 int64_t migrate_xbzrle_cache_size(void)
1644 {
1645     MigrationState *s;
1646 
1647     s = migrate_get_current();
1648 
1649     return s->parameters.xbzrle_cache_size;
1650 }
1651 
1652 bool migrate_use_block(void)
1653 {
1654     MigrationState *s;
1655 
1656     s = migrate_get_current();
1657 
1658     return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
1659 }
1660 
1661 bool migrate_use_return_path(void)
1662 {
1663     MigrationState *s;
1664 
1665     s = migrate_get_current();
1666 
1667     return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
1668 }
1669 
1670 bool migrate_use_block_incremental(void)
1671 {
1672     MigrationState *s;
1673 
1674     s = migrate_get_current();
1675 
1676     return s->parameters.block_incremental;
1677 }
1678 
1679 /* migration thread support */
1680 /*
1681  * Something bad happened to the RP stream, mark an error
1682  * The caller shall print or trace something to indicate why
1683  */
1684 static void mark_source_rp_bad(MigrationState *s)
1685 {
1686     s->rp_state.error = true;
1687 }
1688 
1689 static struct rp_cmd_args {
1690     ssize_t     len; /* -1 = variable */
1691     const char *name;
1692 } rp_cmd_args[] = {
1693     [MIG_RP_MSG_INVALID]        = { .len = -1, .name = "INVALID" },
1694     [MIG_RP_MSG_SHUT]           = { .len =  4, .name = "SHUT" },
1695     [MIG_RP_MSG_PONG]           = { .len =  4, .name = "PONG" },
1696     [MIG_RP_MSG_REQ_PAGES]      = { .len = 12, .name = "REQ_PAGES" },
1697     [MIG_RP_MSG_REQ_PAGES_ID]   = { .len = -1, .name = "REQ_PAGES_ID" },
1698     [MIG_RP_MSG_MAX]            = { .len = -1, .name = "MAX" },
1699 };
1700 
1701 /*
1702  * Process a request for pages received on the return path,
1703  * We're allowed to send more than requested (e.g. to round to our page size)
1704  * and we don't need to send pages that have already been sent.
1705  */
1706 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1707                                        ram_addr_t start, size_t len)
1708 {
1709     long our_host_ps = getpagesize();
1710 
1711     trace_migrate_handle_rp_req_pages(rbname, start, len);
1712 
1713     /*
1714      * Since we currently insist on matching page sizes, just sanity check
1715      * we're being asked for whole host pages.
1716      */
1717     if (start & (our_host_ps-1) ||
1718        (len & (our_host_ps-1))) {
1719         error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1720                      " len: %zd", __func__, start, len);
1721         mark_source_rp_bad(ms);
1722         return;
1723     }
1724 
1725     if (ram_save_queue_pages(rbname, start, len)) {
1726         mark_source_rp_bad(ms);
1727     }
1728 }
1729 
1730 /*
1731  * Handles messages sent on the return path towards the source VM
1732  *
1733  */
1734 static void *source_return_path_thread(void *opaque)
1735 {
1736     MigrationState *ms = opaque;
1737     QEMUFile *rp = ms->rp_state.from_dst_file;
1738     uint16_t header_len, header_type;
1739     uint8_t buf[512];
1740     uint32_t tmp32, sibling_error;
1741     ram_addr_t start = 0; /* =0 to silence warning */
1742     size_t  len = 0, expected_len;
1743     int res;
1744 
1745     trace_source_return_path_thread_entry();
1746     while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1747            migration_is_setup_or_active(ms->state)) {
1748         trace_source_return_path_thread_loop_top();
1749         header_type = qemu_get_be16(rp);
1750         header_len = qemu_get_be16(rp);
1751 
1752         if (qemu_file_get_error(rp)) {
1753             mark_source_rp_bad(ms);
1754             goto out;
1755         }
1756 
1757         if (header_type >= MIG_RP_MSG_MAX ||
1758             header_type == MIG_RP_MSG_INVALID) {
1759             error_report("RP: Received invalid message 0x%04x length 0x%04x",
1760                     header_type, header_len);
1761             mark_source_rp_bad(ms);
1762             goto out;
1763         }
1764 
1765         if ((rp_cmd_args[header_type].len != -1 &&
1766             header_len != rp_cmd_args[header_type].len) ||
1767             header_len > sizeof(buf)) {
1768             error_report("RP: Received '%s' message (0x%04x) with"
1769                     "incorrect length %d expecting %zu",
1770                     rp_cmd_args[header_type].name, header_type, header_len,
1771                     (size_t)rp_cmd_args[header_type].len);
1772             mark_source_rp_bad(ms);
1773             goto out;
1774         }
1775 
1776         /* We know we've got a valid header by this point */
1777         res = qemu_get_buffer(rp, buf, header_len);
1778         if (res != header_len) {
1779             error_report("RP: Failed reading data for message 0x%04x"
1780                          " read %d expected %d",
1781                          header_type, res, header_len);
1782             mark_source_rp_bad(ms);
1783             goto out;
1784         }
1785 
1786         /* OK, we have the message and the data */
1787         switch (header_type) {
1788         case MIG_RP_MSG_SHUT:
1789             sibling_error = ldl_be_p(buf);
1790             trace_source_return_path_thread_shut(sibling_error);
1791             if (sibling_error) {
1792                 error_report("RP: Sibling indicated error %d", sibling_error);
1793                 mark_source_rp_bad(ms);
1794             }
1795             /*
1796              * We'll let the main thread deal with closing the RP
1797              * we could do a shutdown(2) on it, but we're the only user
1798              * anyway, so there's nothing gained.
1799              */
1800             goto out;
1801 
1802         case MIG_RP_MSG_PONG:
1803             tmp32 = ldl_be_p(buf);
1804             trace_source_return_path_thread_pong(tmp32);
1805             break;
1806 
1807         case MIG_RP_MSG_REQ_PAGES:
1808             start = ldq_be_p(buf);
1809             len = ldl_be_p(buf + 8);
1810             migrate_handle_rp_req_pages(ms, NULL, start, len);
1811             break;
1812 
1813         case MIG_RP_MSG_REQ_PAGES_ID:
1814             expected_len = 12 + 1; /* header + termination */
1815 
1816             if (header_len >= expected_len) {
1817                 start = ldq_be_p(buf);
1818                 len = ldl_be_p(buf + 8);
1819                 /* Now we expect an idstr */
1820                 tmp32 = buf[12]; /* Length of the following idstr */
1821                 buf[13 + tmp32] = '\0';
1822                 expected_len += tmp32;
1823             }
1824             if (header_len != expected_len) {
1825                 error_report("RP: Req_Page_id with length %d expecting %zd",
1826                         header_len, expected_len);
1827                 mark_source_rp_bad(ms);
1828                 goto out;
1829             }
1830             migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1831             break;
1832 
1833         default:
1834             break;
1835         }
1836     }
1837     if (qemu_file_get_error(rp)) {
1838         trace_source_return_path_thread_bad_end();
1839         mark_source_rp_bad(ms);
1840     }
1841 
1842     trace_source_return_path_thread_end();
1843 out:
1844     ms->rp_state.from_dst_file = NULL;
1845     qemu_fclose(rp);
1846     return NULL;
1847 }
1848 
1849 static int open_return_path_on_source(MigrationState *ms)
1850 {
1851 
1852     ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
1853     if (!ms->rp_state.from_dst_file) {
1854         return -1;
1855     }
1856 
1857     trace_open_return_path_on_source();
1858     qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1859                        source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1860 
1861     trace_open_return_path_on_source_continue();
1862 
1863     return 0;
1864 }
1865 
1866 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1867 static int await_return_path_close_on_source(MigrationState *ms)
1868 {
1869     /*
1870      * If this is a normal exit then the destination will send a SHUT and the
1871      * rp_thread will exit, however if there's an error we need to cause
1872      * it to exit.
1873      */
1874     if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
1875         /*
1876          * shutdown(2), if we have it, will cause it to unblock if it's stuck
1877          * waiting for the destination.
1878          */
1879         qemu_file_shutdown(ms->rp_state.from_dst_file);
1880         mark_source_rp_bad(ms);
1881     }
1882     trace_await_return_path_close_on_source_joining();
1883     qemu_thread_join(&ms->rp_state.rp_thread);
1884     trace_await_return_path_close_on_source_close();
1885     return ms->rp_state.error;
1886 }
1887 
1888 /*
1889  * Switch from normal iteration to postcopy
1890  * Returns non-0 on error
1891  */
1892 static int postcopy_start(MigrationState *ms)
1893 {
1894     int ret;
1895     QIOChannelBuffer *bioc;
1896     QEMUFile *fb;
1897     int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1898     bool restart_block = false;
1899     int cur_state = MIGRATION_STATUS_ACTIVE;
1900     if (!migrate_pause_before_switchover()) {
1901         migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1902                           MIGRATION_STATUS_POSTCOPY_ACTIVE);
1903     }
1904 
1905     trace_postcopy_start();
1906     qemu_mutex_lock_iothread();
1907     trace_postcopy_start_set_run();
1908 
1909     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1910     global_state_store();
1911     ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1912     if (ret < 0) {
1913         goto fail;
1914     }
1915 
1916     ret = migration_maybe_pause(ms, &cur_state,
1917                                 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1918     if (ret < 0) {
1919         goto fail;
1920     }
1921 
1922     ret = bdrv_inactivate_all();
1923     if (ret < 0) {
1924         goto fail;
1925     }
1926     restart_block = true;
1927 
1928     /*
1929      * Cause any non-postcopiable, but iterative devices to
1930      * send out their final data.
1931      */
1932     qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1933 
1934     /*
1935      * in Finish migrate and with the io-lock held everything should
1936      * be quiet, but we've potentially still got dirty pages and we
1937      * need to tell the destination to throw any pages it's already received
1938      * that are dirty
1939      */
1940     if (migrate_postcopy_ram()) {
1941         if (ram_postcopy_send_discard_bitmap(ms)) {
1942             error_report("postcopy send discard bitmap failed");
1943             goto fail;
1944         }
1945     }
1946 
1947     /*
1948      * send rest of state - note things that are doing postcopy
1949      * will notice we're in POSTCOPY_ACTIVE and not actually
1950      * wrap their state up here
1951      */
1952     qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
1953     if (migrate_postcopy_ram()) {
1954         /* Ping just for debugging, helps line traces up */
1955         qemu_savevm_send_ping(ms->to_dst_file, 2);
1956     }
1957 
1958     /*
1959      * While loading the device state we may trigger page transfer
1960      * requests and the fd must be free to process those, and thus
1961      * the destination must read the whole device state off the fd before
1962      * it starts processing it.  Unfortunately the ad-hoc migration format
1963      * doesn't allow the destination to know the size to read without fully
1964      * parsing it through each devices load-state code (especially the open
1965      * coded devices that use get/put).
1966      * So we wrap the device state up in a package with a length at the start;
1967      * to do this we use a qemu_buf to hold the whole of the device state.
1968      */
1969     bioc = qio_channel_buffer_new(4096);
1970     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
1971     fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
1972     object_unref(OBJECT(bioc));
1973 
1974     /*
1975      * Make sure the receiver can get incoming pages before we send the rest
1976      * of the state
1977      */
1978     qemu_savevm_send_postcopy_listen(fb);
1979 
1980     qemu_savevm_state_complete_precopy(fb, false, false);
1981     if (migrate_postcopy_ram()) {
1982         qemu_savevm_send_ping(fb, 3);
1983     }
1984 
1985     qemu_savevm_send_postcopy_run(fb);
1986 
1987     /* <><> end of stuff going into the package */
1988 
1989     /* Last point of recovery; as soon as we send the package the destination
1990      * can open devices and potentially start running.
1991      * Lets just check again we've not got any errors.
1992      */
1993     ret = qemu_file_get_error(ms->to_dst_file);
1994     if (ret) {
1995         error_report("postcopy_start: Migration stream errored (pre package)");
1996         goto fail_closefb;
1997     }
1998 
1999     restart_block = false;
2000 
2001     /* Now send that blob */
2002     if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2003         goto fail_closefb;
2004     }
2005     qemu_fclose(fb);
2006 
2007     /* Send a notify to give a chance for anything that needs to happen
2008      * at the transition to postcopy and after the device state; in particular
2009      * spice needs to trigger a transition now
2010      */
2011     ms->postcopy_after_devices = true;
2012     notifier_list_notify(&migration_state_notifiers, ms);
2013 
2014     ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2015 
2016     qemu_mutex_unlock_iothread();
2017 
2018     if (migrate_postcopy_ram()) {
2019         /*
2020          * Although this ping is just for debug, it could potentially be
2021          * used for getting a better measurement of downtime at the source.
2022          */
2023         qemu_savevm_send_ping(ms->to_dst_file, 4);
2024     }
2025 
2026     if (migrate_release_ram()) {
2027         ram_postcopy_migrated_memory_release(ms);
2028     }
2029 
2030     ret = qemu_file_get_error(ms->to_dst_file);
2031     if (ret) {
2032         error_report("postcopy_start: Migration stream errored");
2033         migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2034                               MIGRATION_STATUS_FAILED);
2035     }
2036 
2037     return ret;
2038 
2039 fail_closefb:
2040     qemu_fclose(fb);
2041 fail:
2042     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2043                           MIGRATION_STATUS_FAILED);
2044     if (restart_block) {
2045         /* A failure happened early enough that we know the destination hasn't
2046          * accessed block devices, so we're safe to recover.
2047          */
2048         Error *local_err = NULL;
2049 
2050         bdrv_invalidate_cache_all(&local_err);
2051         if (local_err) {
2052             error_report_err(local_err);
2053         }
2054     }
2055     qemu_mutex_unlock_iothread();
2056     return -1;
2057 }
2058 
2059 /**
2060  * migration_maybe_pause: Pause if required to by
2061  * migrate_pause_before_switchover called with the iothread locked
2062  * Returns: 0 on success
2063  */
2064 static int migration_maybe_pause(MigrationState *s,
2065                                  int *current_active_state,
2066                                  int new_state)
2067 {
2068     if (!migrate_pause_before_switchover()) {
2069         return 0;
2070     }
2071 
2072     /* Since leaving this state is not atomic with posting the semaphore
2073      * it's possible that someone could have issued multiple migrate_continue
2074      * and the semaphore is incorrectly positive at this point;
2075      * the docs say it's undefined to reinit a semaphore that's already
2076      * init'd, so use timedwait to eat up any existing posts.
2077      */
2078     while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2079         /* This block intentionally left blank */
2080     }
2081 
2082     qemu_mutex_unlock_iothread();
2083     migrate_set_state(&s->state, *current_active_state,
2084                       MIGRATION_STATUS_PRE_SWITCHOVER);
2085     qemu_sem_wait(&s->pause_sem);
2086     migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2087                       new_state);
2088     *current_active_state = new_state;
2089     qemu_mutex_lock_iothread();
2090 
2091     return s->state == new_state ? 0 : -EINVAL;
2092 }
2093 
2094 /**
2095  * migration_completion: Used by migration_thread when there's not much left.
2096  *   The caller 'breaks' the loop when this returns.
2097  *
2098  * @s: Current migration state
2099  */
2100 static void migration_completion(MigrationState *s)
2101 {
2102     int ret;
2103     int current_active_state = s->state;
2104 
2105     if (s->state == MIGRATION_STATUS_ACTIVE) {
2106         qemu_mutex_lock_iothread();
2107         s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2108         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2109         s->vm_was_running = runstate_is_running();
2110         ret = global_state_store();
2111 
2112         if (!ret) {
2113             bool inactivate = !migrate_colo_enabled();
2114             ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2115             if (ret >= 0) {
2116                 ret = migration_maybe_pause(s, &current_active_state,
2117                                             MIGRATION_STATUS_DEVICE);
2118             }
2119             if (ret >= 0) {
2120                 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2121                 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2122                                                          inactivate);
2123             }
2124             if (inactivate && ret >= 0) {
2125                 s->block_inactive = true;
2126             }
2127         }
2128         qemu_mutex_unlock_iothread();
2129 
2130         if (ret < 0) {
2131             goto fail;
2132         }
2133     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2134         trace_migration_completion_postcopy_end();
2135 
2136         qemu_savevm_state_complete_postcopy(s->to_dst_file);
2137         trace_migration_completion_postcopy_end_after_complete();
2138     }
2139 
2140     /*
2141      * If rp was opened we must clean up the thread before
2142      * cleaning everything else up (since if there are no failures
2143      * it will wait for the destination to send it's status in
2144      * a SHUT command).
2145      */
2146     if (s->rp_state.from_dst_file) {
2147         int rp_error;
2148         trace_migration_return_path_end_before();
2149         rp_error = await_return_path_close_on_source(s);
2150         trace_migration_return_path_end_after(rp_error);
2151         if (rp_error) {
2152             goto fail_invalidate;
2153         }
2154     }
2155 
2156     if (qemu_file_get_error(s->to_dst_file)) {
2157         trace_migration_completion_file_err();
2158         goto fail_invalidate;
2159     }
2160 
2161     if (!migrate_colo_enabled()) {
2162         migrate_set_state(&s->state, current_active_state,
2163                           MIGRATION_STATUS_COMPLETED);
2164     }
2165 
2166     return;
2167 
2168 fail_invalidate:
2169     /* If not doing postcopy, vm_start() will be called: let's regain
2170      * control on images.
2171      */
2172     if (s->state == MIGRATION_STATUS_ACTIVE ||
2173         s->state == MIGRATION_STATUS_DEVICE) {
2174         Error *local_err = NULL;
2175 
2176         qemu_mutex_lock_iothread();
2177         bdrv_invalidate_cache_all(&local_err);
2178         if (local_err) {
2179             error_report_err(local_err);
2180         } else {
2181             s->block_inactive = false;
2182         }
2183         qemu_mutex_unlock_iothread();
2184     }
2185 
2186 fail:
2187     migrate_set_state(&s->state, current_active_state,
2188                       MIGRATION_STATUS_FAILED);
2189 }
2190 
2191 bool migrate_colo_enabled(void)
2192 {
2193     MigrationState *s = migrate_get_current();
2194     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2195 }
2196 
2197 static void migration_calculate_complete(MigrationState *s)
2198 {
2199     uint64_t bytes = qemu_ftell(s->to_dst_file);
2200     int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2201 
2202     s->total_time = end_time - s->start_time;
2203     if (!s->downtime) {
2204         /*
2205          * It's still not set, so we are precopy migration.  For
2206          * postcopy, downtime is calculated during postcopy_start().
2207          */
2208         s->downtime = end_time - s->downtime_start;
2209     }
2210 
2211     if (s->total_time) {
2212         s->mbps = ((double) bytes * 8.0) / s->total_time / 1000;
2213     }
2214 }
2215 
2216 static void migration_update_counters(MigrationState *s,
2217                                       int64_t current_time)
2218 {
2219     uint64_t transferred, time_spent;
2220     double bandwidth;
2221 
2222     if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2223         return;
2224     }
2225 
2226     transferred = qemu_ftell(s->to_dst_file) - s->iteration_initial_bytes;
2227     time_spent = current_time - s->iteration_start_time;
2228     bandwidth = (double)transferred / time_spent;
2229     s->threshold_size = bandwidth * s->parameters.downtime_limit;
2230 
2231     s->mbps = (((double) transferred * 8.0) /
2232                ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2233 
2234     /*
2235      * if we haven't sent anything, we don't want to
2236      * recalculate. 10000 is a small enough number for our purposes
2237      */
2238     if (ram_counters.dirty_pages_rate && transferred > 10000) {
2239         s->expected_downtime = ram_counters.dirty_pages_rate *
2240             qemu_target_page_size() / bandwidth;
2241     }
2242 
2243     qemu_file_reset_rate_limit(s->to_dst_file);
2244 
2245     s->iteration_start_time = current_time;
2246     s->iteration_initial_bytes = qemu_ftell(s->to_dst_file);
2247 
2248     trace_migrate_transferred(transferred, time_spent,
2249                               bandwidth, s->threshold_size);
2250 }
2251 
2252 /* Migration thread iteration status */
2253 typedef enum {
2254     MIG_ITERATE_RESUME,         /* Resume current iteration */
2255     MIG_ITERATE_SKIP,           /* Skip current iteration */
2256     MIG_ITERATE_BREAK,          /* Break the loop */
2257 } MigIterateState;
2258 
2259 /*
2260  * Return true if continue to the next iteration directly, false
2261  * otherwise.
2262  */
2263 static MigIterateState migration_iteration_run(MigrationState *s)
2264 {
2265     uint64_t pending_size, pend_pre, pend_compat, pend_post;
2266     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2267 
2268     qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2269                               &pend_compat, &pend_post);
2270     pending_size = pend_pre + pend_compat + pend_post;
2271 
2272     trace_migrate_pending(pending_size, s->threshold_size,
2273                           pend_pre, pend_compat, pend_post);
2274 
2275     if (pending_size && pending_size >= s->threshold_size) {
2276         /* Still a significant amount to transfer */
2277         if (migrate_postcopy() && !in_postcopy &&
2278             pend_pre <= s->threshold_size &&
2279             atomic_read(&s->start_postcopy)) {
2280             if (postcopy_start(s)) {
2281                 error_report("%s: postcopy failed to start", __func__);
2282             }
2283             return MIG_ITERATE_SKIP;
2284         }
2285         /* Just another iteration step */
2286         qemu_savevm_state_iterate(s->to_dst_file,
2287             s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2288     } else {
2289         trace_migration_thread_low_pending(pending_size);
2290         migration_completion(s);
2291         return MIG_ITERATE_BREAK;
2292     }
2293 
2294     return MIG_ITERATE_RESUME;
2295 }
2296 
2297 static void migration_iteration_finish(MigrationState *s)
2298 {
2299     /* If we enabled cpu throttling for auto-converge, turn it off. */
2300     cpu_throttle_stop();
2301 
2302     qemu_mutex_lock_iothread();
2303     switch (s->state) {
2304     case MIGRATION_STATUS_COMPLETED:
2305         migration_calculate_complete(s);
2306         runstate_set(RUN_STATE_POSTMIGRATE);
2307         break;
2308 
2309     case MIGRATION_STATUS_ACTIVE:
2310         /*
2311          * We should really assert here, but since it's during
2312          * migration, let's try to reduce the usage of assertions.
2313          */
2314         if (!migrate_colo_enabled()) {
2315             error_report("%s: critical error: calling COLO code without "
2316                          "COLO enabled", __func__);
2317         }
2318         migrate_start_colo_process(s);
2319         /*
2320          * Fixme: we will run VM in COLO no matter its old running state.
2321          * After exited COLO, we will keep running.
2322          */
2323         s->vm_was_running = true;
2324         /* Fallthrough */
2325     case MIGRATION_STATUS_FAILED:
2326     case MIGRATION_STATUS_CANCELLED:
2327         if (s->vm_was_running) {
2328             vm_start();
2329         } else {
2330             if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2331                 runstate_set(RUN_STATE_POSTMIGRATE);
2332             }
2333         }
2334         break;
2335 
2336     default:
2337         /* Should not reach here, but if so, forgive the VM. */
2338         error_report("%s: Unknown ending state %d", __func__, s->state);
2339         break;
2340     }
2341     qemu_bh_schedule(s->cleanup_bh);
2342     qemu_mutex_unlock_iothread();
2343 }
2344 
2345 /*
2346  * Master migration thread on the source VM.
2347  * It drives the migration and pumps the data down the outgoing channel.
2348  */
2349 static void *migration_thread(void *opaque)
2350 {
2351     MigrationState *s = opaque;
2352     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2353 
2354     rcu_register_thread();
2355 
2356     s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2357 
2358     qemu_savevm_state_header(s->to_dst_file);
2359 
2360     /*
2361      * If we opened the return path, we need to make sure dst has it
2362      * opened as well.
2363      */
2364     if (s->rp_state.from_dst_file) {
2365         /* Now tell the dest that it should open its end so it can reply */
2366         qemu_savevm_send_open_return_path(s->to_dst_file);
2367 
2368         /* And do a ping that will make stuff easier to debug */
2369         qemu_savevm_send_ping(s->to_dst_file, 1);
2370     }
2371 
2372     if (migrate_postcopy()) {
2373         /*
2374          * Tell the destination that we *might* want to do postcopy later;
2375          * if the other end can't do postcopy it should fail now, nice and
2376          * early.
2377          */
2378         qemu_savevm_send_postcopy_advise(s->to_dst_file);
2379     }
2380 
2381     qemu_savevm_state_setup(s->to_dst_file);
2382 
2383     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
2384     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2385                       MIGRATION_STATUS_ACTIVE);
2386 
2387     trace_migration_thread_setup_complete();
2388 
2389     while (s->state == MIGRATION_STATUS_ACTIVE ||
2390            s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2391         int64_t current_time;
2392 
2393         if (!qemu_file_rate_limit(s->to_dst_file)) {
2394             MigIterateState iter_state = migration_iteration_run(s);
2395             if (iter_state == MIG_ITERATE_SKIP) {
2396                 continue;
2397             } else if (iter_state == MIG_ITERATE_BREAK) {
2398                 break;
2399             }
2400         }
2401 
2402         if (qemu_file_get_error(s->to_dst_file)) {
2403             if (migration_is_setup_or_active(s->state)) {
2404                 migrate_set_state(&s->state, s->state,
2405                                   MIGRATION_STATUS_FAILED);
2406             }
2407             trace_migration_thread_file_err();
2408             break;
2409         }
2410 
2411         current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2412 
2413         migration_update_counters(s, current_time);
2414 
2415         if (qemu_file_rate_limit(s->to_dst_file)) {
2416             /* usleep expects microseconds */
2417             g_usleep((s->iteration_start_time + BUFFER_DELAY -
2418                       current_time) * 1000);
2419         }
2420     }
2421 
2422     trace_migration_thread_after_loop();
2423     migration_iteration_finish(s);
2424     rcu_unregister_thread();
2425     return NULL;
2426 }
2427 
2428 void migrate_fd_connect(MigrationState *s, Error *error_in)
2429 {
2430     s->expected_downtime = s->parameters.downtime_limit;
2431     s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
2432     if (error_in) {
2433         migrate_fd_error(s, error_in);
2434         migrate_fd_cleanup(s);
2435         return;
2436     }
2437 
2438     qemu_file_set_blocking(s->to_dst_file, true);
2439     qemu_file_set_rate_limit(s->to_dst_file,
2440                              s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
2441 
2442     /* Notify before starting migration thread */
2443     notifier_list_notify(&migration_state_notifiers, s);
2444 
2445     /*
2446      * Open the return path. For postcopy, it is used exclusively. For
2447      * precopy, only if user specified "return-path" capability would
2448      * QEMU uses the return path.
2449      */
2450     if (migrate_postcopy_ram() || migrate_use_return_path()) {
2451         if (open_return_path_on_source(s)) {
2452             error_report("Unable to open return-path for postcopy");
2453             migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2454                               MIGRATION_STATUS_FAILED);
2455             migrate_fd_cleanup(s);
2456             return;
2457         }
2458     }
2459 
2460     if (multifd_save_setup() != 0) {
2461         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2462                           MIGRATION_STATUS_FAILED);
2463         migrate_fd_cleanup(s);
2464         return;
2465     }
2466     qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
2467                        QEMU_THREAD_JOINABLE);
2468     s->migration_thread_running = true;
2469 }
2470 
2471 void migration_global_dump(Monitor *mon)
2472 {
2473     MigrationState *ms = migrate_get_current();
2474 
2475     monitor_printf(mon, "globals:\n");
2476     monitor_printf(mon, "store-global-state: %s\n",
2477                    ms->store_global_state ? "on" : "off");
2478     monitor_printf(mon, "only-migratable: %s\n",
2479                    ms->only_migratable ? "on" : "off");
2480     monitor_printf(mon, "send-configuration: %s\n",
2481                    ms->send_configuration ? "on" : "off");
2482     monitor_printf(mon, "send-section-footer: %s\n",
2483                    ms->send_section_footer ? "on" : "off");
2484 }
2485 
2486 #define DEFINE_PROP_MIG_CAP(name, x)             \
2487     DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2488 
2489 static Property migration_properties[] = {
2490     DEFINE_PROP_BOOL("store-global-state", MigrationState,
2491                      store_global_state, true),
2492     DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
2493     DEFINE_PROP_BOOL("send-configuration", MigrationState,
2494                      send_configuration, true),
2495     DEFINE_PROP_BOOL("send-section-footer", MigrationState,
2496                      send_section_footer, true),
2497 
2498     /* Migration parameters */
2499     DEFINE_PROP_UINT8("x-compress-level", MigrationState,
2500                       parameters.compress_level,
2501                       DEFAULT_MIGRATE_COMPRESS_LEVEL),
2502     DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
2503                       parameters.compress_threads,
2504                       DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
2505     DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
2506                       parameters.decompress_threads,
2507                       DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
2508     DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
2509                       parameters.cpu_throttle_initial,
2510                       DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
2511     DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
2512                       parameters.cpu_throttle_increment,
2513                       DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
2514     DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
2515                       parameters.max_bandwidth, MAX_THROTTLE),
2516     DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
2517                       parameters.downtime_limit,
2518                       DEFAULT_MIGRATE_SET_DOWNTIME),
2519     DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
2520                       parameters.x_checkpoint_delay,
2521                       DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
2522     DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
2523                       parameters.x_multifd_channels,
2524                       DEFAULT_MIGRATE_MULTIFD_CHANNELS),
2525     DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
2526                       parameters.x_multifd_page_count,
2527                       DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
2528     DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
2529                       parameters.xbzrle_cache_size,
2530                       DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
2531 
2532     /* Migration capabilities */
2533     DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
2534     DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
2535     DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
2536     DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
2537     DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
2538     DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
2539     DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
2540     DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
2541     DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
2542     DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
2543     DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
2544     DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
2545 
2546     DEFINE_PROP_END_OF_LIST(),
2547 };
2548 
2549 static void migration_class_init(ObjectClass *klass, void *data)
2550 {
2551     DeviceClass *dc = DEVICE_CLASS(klass);
2552 
2553     dc->user_creatable = false;
2554     dc->props = migration_properties;
2555 }
2556 
2557 static void migration_instance_finalize(Object *obj)
2558 {
2559     MigrationState *ms = MIGRATION_OBJ(obj);
2560     MigrationParameters *params = &ms->parameters;
2561 
2562     qemu_mutex_destroy(&ms->error_mutex);
2563     g_free(params->tls_hostname);
2564     g_free(params->tls_creds);
2565     qemu_sem_destroy(&ms->pause_sem);
2566     error_free(ms->error);
2567 }
2568 
2569 static void migration_instance_init(Object *obj)
2570 {
2571     MigrationState *ms = MIGRATION_OBJ(obj);
2572     MigrationParameters *params = &ms->parameters;
2573 
2574     ms->state = MIGRATION_STATUS_NONE;
2575     ms->mbps = -1;
2576     qemu_sem_init(&ms->pause_sem, 0);
2577     qemu_mutex_init(&ms->error_mutex);
2578 
2579     params->tls_hostname = g_strdup("");
2580     params->tls_creds = g_strdup("");
2581 
2582     /* Set has_* up only for parameter checks */
2583     params->has_compress_level = true;
2584     params->has_compress_threads = true;
2585     params->has_decompress_threads = true;
2586     params->has_cpu_throttle_initial = true;
2587     params->has_cpu_throttle_increment = true;
2588     params->has_max_bandwidth = true;
2589     params->has_downtime_limit = true;
2590     params->has_x_checkpoint_delay = true;
2591     params->has_block_incremental = true;
2592     params->has_x_multifd_channels = true;
2593     params->has_x_multifd_page_count = true;
2594     params->has_xbzrle_cache_size = true;
2595 }
2596 
2597 /*
2598  * Return true if check pass, false otherwise. Error will be put
2599  * inside errp if provided.
2600  */
2601 static bool migration_object_check(MigrationState *ms, Error **errp)
2602 {
2603     MigrationCapabilityStatusList *head = NULL;
2604     /* Assuming all off */
2605     bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
2606     int i;
2607 
2608     if (!migrate_params_check(&ms->parameters, errp)) {
2609         return false;
2610     }
2611 
2612     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
2613         if (ms->enabled_capabilities[i]) {
2614             head = migrate_cap_add(head, i, true);
2615         }
2616     }
2617 
2618     ret = migrate_caps_check(cap_list, head, errp);
2619 
2620     /* It works with head == NULL */
2621     qapi_free_MigrationCapabilityStatusList(head);
2622 
2623     return ret;
2624 }
2625 
2626 static const TypeInfo migration_type = {
2627     .name = TYPE_MIGRATION,
2628     /*
2629      * NOTE: TYPE_MIGRATION is not really a device, as the object is
2630      * not created using qdev_create(), it is not attached to the qdev
2631      * device tree, and it is never realized.
2632      *
2633      * TODO: Make this TYPE_OBJECT once QOM provides something like
2634      * TYPE_DEVICE's "-global" properties.
2635      */
2636     .parent = TYPE_DEVICE,
2637     .class_init = migration_class_init,
2638     .class_size = sizeof(MigrationClass),
2639     .instance_size = sizeof(MigrationState),
2640     .instance_init = migration_instance_init,
2641     .instance_finalize = migration_instance_finalize,
2642 };
2643 
2644 static void register_migration_types(void)
2645 {
2646     type_register_static(&migration_type);
2647 }
2648 
2649 type_init(register_migration_types);
2650