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