Merge remote-tracking branch 'remotes/dgilbert/tags/pull-hmp-20180320' into staging
[qemu/ar7.git] / migration / migration.c
blobfc629e5965fd19dd212a22f2fc54fbd5edf7b192
1 /*
2 * QEMU live migration
4 * Copyright IBM, Corp. 2008
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
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.
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"
49 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
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)
56 /* Time in milliseconds we are allowed to stop the source,
57 * for sending the last part */
58 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
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)
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
75 /* Migration XBZRLE default cache size */
76 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
78 /* The delay time (in ms) between two COLO checkpoints
79 * Note: Please change this default value to 10000 when we support hybrid mode.
81 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
82 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
83 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
85 static NotifierList migration_state_notifiers =
86 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
88 static bool deferred_incoming;
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 ) */
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) */
99 MIG_RP_MSG_MAX
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 */
106 static MigrationState *current_migration;
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);
113 void migration_object_init(void)
115 MachineState *ms = MACHINE(qdev_get_machine());
116 Error *err = NULL;
118 /* This can only be called once. */
119 assert(!current_migration);
120 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
122 if (!migration_object_check(current_migration, &err)) {
123 error_report_err(err);
124 exit(1);
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.
132 if (ms->enforce_config_section) {
133 current_migration->send_configuration = true;
137 void migration_object_finalize(void)
139 object_unref(OBJECT(current_migration));
142 /* For outgoing */
143 MigrationState *migrate_get_current(void)
145 /* This can only be called after the object created. */
146 assert(current_migration);
147 return current_migration;
150 MigrationIncomingState *migration_incoming_get_current(void)
152 static bool once;
153 static MigrationIncomingState mis_current;
155 if (!once) {
156 mis_current.state = MIGRATION_STATUS_NONE;
157 memset(&mis_current, 0, sizeof(MigrationIncomingState));
158 mis_current.postcopy_remote_fds = g_array_new(FALSE, TRUE,
159 sizeof(struct PostCopyFD));
160 qemu_mutex_init(&mis_current.rp_mutex);
161 qemu_event_init(&mis_current.main_thread_load_event, false);
163 init_dirty_bitmap_incoming_migration();
165 once = true;
167 return &mis_current;
170 void migration_incoming_state_destroy(void)
172 struct MigrationIncomingState *mis = migration_incoming_get_current();
174 if (mis->to_src_file) {
175 /* Tell source that we are done */
176 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
177 qemu_fclose(mis->to_src_file);
178 mis->to_src_file = NULL;
181 if (mis->from_src_file) {
182 qemu_fclose(mis->from_src_file);
183 mis->from_src_file = NULL;
185 if (mis->postcopy_remote_fds) {
186 g_array_free(mis->postcopy_remote_fds, TRUE);
187 mis->postcopy_remote_fds = NULL;
190 qemu_event_reset(&mis->main_thread_load_event);
193 static void migrate_generate_event(int new_state)
195 if (migrate_use_events()) {
196 qapi_event_send_migration(new_state, &error_abort);
201 * Called on -incoming with a defer: uri.
202 * The migration can be started later after any parameters have been
203 * changed.
205 static void deferred_incoming_migration(Error **errp)
207 if (deferred_incoming) {
208 error_setg(errp, "Incoming migration already deferred");
210 deferred_incoming = true;
214 * Send a message on the return channel back to the source
215 * of the migration.
217 static int migrate_send_rp_message(MigrationIncomingState *mis,
218 enum mig_rp_message_type message_type,
219 uint16_t len, void *data)
221 int ret = 0;
223 trace_migrate_send_rp_message((int)message_type, len);
224 qemu_mutex_lock(&mis->rp_mutex);
227 * It's possible that the file handle got lost due to network
228 * failures.
230 if (!mis->to_src_file) {
231 ret = -EIO;
232 goto error;
235 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
236 qemu_put_be16(mis->to_src_file, len);
237 qemu_put_buffer(mis->to_src_file, data, len);
238 qemu_fflush(mis->to_src_file);
240 /* It's possible that qemu file got error during sending */
241 ret = qemu_file_get_error(mis->to_src_file);
243 error:
244 qemu_mutex_unlock(&mis->rp_mutex);
245 return ret;
248 /* Request a range of pages from the source VM at the given
249 * start address.
250 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
251 * as the last request (a name must have been given previously)
252 * Start: Address offset within the RB
253 * Len: Length in bytes required - must be a multiple of pagesize
255 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
256 ram_addr_t start, size_t len)
258 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
259 size_t msglen = 12; /* start + len */
260 enum mig_rp_message_type msg_type;
262 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
263 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
265 if (rbname) {
266 int rbname_len = strlen(rbname);
267 assert(rbname_len < 256);
269 bufc[msglen++] = rbname_len;
270 memcpy(bufc + msglen, rbname, rbname_len);
271 msglen += rbname_len;
272 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
273 } else {
274 msg_type = MIG_RP_MSG_REQ_PAGES;
277 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
280 void qemu_start_incoming_migration(const char *uri, Error **errp)
282 const char *p;
284 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
285 if (!strcmp(uri, "defer")) {
286 deferred_incoming_migration(errp);
287 } else if (strstart(uri, "tcp:", &p)) {
288 tcp_start_incoming_migration(p, errp);
289 #ifdef CONFIG_RDMA
290 } else if (strstart(uri, "rdma:", &p)) {
291 rdma_start_incoming_migration(p, errp);
292 #endif
293 } else if (strstart(uri, "exec:", &p)) {
294 exec_start_incoming_migration(p, errp);
295 } else if (strstart(uri, "unix:", &p)) {
296 unix_start_incoming_migration(p, errp);
297 } else if (strstart(uri, "fd:", &p)) {
298 fd_start_incoming_migration(p, errp);
299 } else {
300 error_setg(errp, "unknown migration protocol: %s", uri);
304 static void process_incoming_migration_bh(void *opaque)
306 Error *local_err = NULL;
307 MigrationIncomingState *mis = opaque;
309 /* Make sure all file formats flush their mutable metadata.
310 * If we get an error here, just don't restart the VM yet. */
311 bdrv_invalidate_cache_all(&local_err);
312 if (local_err) {
313 error_report_err(local_err);
314 local_err = NULL;
315 autostart = false;
319 * This must happen after all error conditions are dealt with and
320 * we're sure the VM is going to be running on this host.
322 qemu_announce_self();
324 if (multifd_load_cleanup(&local_err) != 0) {
325 error_report_err(local_err);
326 autostart = false;
328 /* If global state section was not received or we are in running
329 state, we need to obey autostart. Any other state is set with
330 runstate_set. */
332 dirty_bitmap_mig_before_vm_start();
334 if (!global_state_received() ||
335 global_state_get_runstate() == RUN_STATE_RUNNING) {
336 if (autostart) {
337 vm_start();
338 } else {
339 runstate_set(RUN_STATE_PAUSED);
341 } else {
342 runstate_set(global_state_get_runstate());
345 * This must happen after any state changes since as soon as an external
346 * observer sees this event they might start to prod at the VM assuming
347 * it's ready to use.
349 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
350 MIGRATION_STATUS_COMPLETED);
351 qemu_bh_delete(mis->bh);
352 migration_incoming_state_destroy();
355 static void process_incoming_migration_co(void *opaque)
357 MigrationIncomingState *mis = migration_incoming_get_current();
358 PostcopyState ps;
359 int ret;
361 assert(mis->from_src_file);
362 mis->largest_page_size = qemu_ram_pagesize_largest();
363 postcopy_state_set(POSTCOPY_INCOMING_NONE);
364 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
365 MIGRATION_STATUS_ACTIVE);
366 ret = qemu_loadvm_state(mis->from_src_file);
368 ps = postcopy_state_get();
369 trace_process_incoming_migration_co_end(ret, ps);
370 if (ps != POSTCOPY_INCOMING_NONE) {
371 if (ps == POSTCOPY_INCOMING_ADVISE) {
373 * Where a migration had postcopy enabled (and thus went to advise)
374 * but managed to complete within the precopy period, we can use
375 * the normal exit.
377 postcopy_ram_incoming_cleanup(mis);
378 } else if (ret >= 0) {
380 * Postcopy was started, cleanup should happen at the end of the
381 * postcopy thread.
383 trace_process_incoming_migration_co_postcopy_end_main();
384 return;
386 /* Else if something went wrong then just fall out of the normal exit */
389 /* we get COLO info, and know if we are in COLO mode */
390 if (!ret && migration_incoming_enable_colo()) {
391 mis->migration_incoming_co = qemu_coroutine_self();
392 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
393 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
394 mis->have_colo_incoming_thread = true;
395 qemu_coroutine_yield();
397 /* Wait checkpoint incoming thread exit before free resource */
398 qemu_thread_join(&mis->colo_incoming_thread);
401 if (ret < 0) {
402 Error *local_err = NULL;
404 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
405 MIGRATION_STATUS_FAILED);
406 error_report("load of migration failed: %s", strerror(-ret));
407 qemu_fclose(mis->from_src_file);
408 if (multifd_load_cleanup(&local_err) != 0) {
409 error_report_err(local_err);
411 exit(EXIT_FAILURE);
413 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
414 qemu_bh_schedule(mis->bh);
417 static void migration_incoming_setup(QEMUFile *f)
419 MigrationIncomingState *mis = migration_incoming_get_current();
421 if (multifd_load_setup() != 0) {
422 /* We haven't been able to create multifd threads
423 nothing better to do */
424 exit(EXIT_FAILURE);
427 if (!mis->from_src_file) {
428 mis->from_src_file = f;
430 qemu_file_set_blocking(f, false);
433 static void migration_incoming_process(void)
435 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
436 qemu_coroutine_enter(co);
439 void migration_fd_process_incoming(QEMUFile *f)
441 migration_incoming_setup(f);
442 migration_incoming_process();
445 void migration_ioc_process_incoming(QIOChannel *ioc)
447 MigrationIncomingState *mis = migration_incoming_get_current();
449 if (!mis->from_src_file) {
450 QEMUFile *f = qemu_fopen_channel_input(ioc);
451 migration_fd_process_incoming(f);
453 /* We still only have a single channel. Nothing to do here yet */
457 * @migration_has_all_channels: We have received all channels that we need
459 * Returns true when we have got connections to all the channels that
460 * we need for migration.
462 bool migration_has_all_channels(void)
464 return true;
468 * Send a 'SHUT' message on the return channel with the given value
469 * to indicate that we've finished with the RP. Non-0 value indicates
470 * error.
472 void migrate_send_rp_shut(MigrationIncomingState *mis,
473 uint32_t value)
475 uint32_t buf;
477 buf = cpu_to_be32(value);
478 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
482 * Send a 'PONG' message on the return channel with the given value
483 * (normally in response to a 'PING')
485 void migrate_send_rp_pong(MigrationIncomingState *mis,
486 uint32_t value)
488 uint32_t buf;
490 buf = cpu_to_be32(value);
491 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
494 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
496 MigrationCapabilityStatusList *head = NULL;
497 MigrationCapabilityStatusList *caps;
498 MigrationState *s = migrate_get_current();
499 int i;
501 caps = NULL; /* silence compiler warning */
502 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
503 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
504 if (i == MIGRATION_CAPABILITY_BLOCK) {
505 continue;
507 #endif
508 if (head == NULL) {
509 head = g_malloc0(sizeof(*caps));
510 caps = head;
511 } else {
512 caps->next = g_malloc0(sizeof(*caps));
513 caps = caps->next;
515 caps->value =
516 g_malloc(sizeof(*caps->value));
517 caps->value->capability = i;
518 caps->value->state = s->enabled_capabilities[i];
521 return head;
524 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
526 MigrationParameters *params;
527 MigrationState *s = migrate_get_current();
529 /* TODO use QAPI_CLONE() instead of duplicating it inline */
530 params = g_malloc0(sizeof(*params));
531 params->has_compress_level = true;
532 params->compress_level = s->parameters.compress_level;
533 params->has_compress_threads = true;
534 params->compress_threads = s->parameters.compress_threads;
535 params->has_decompress_threads = true;
536 params->decompress_threads = s->parameters.decompress_threads;
537 params->has_cpu_throttle_initial = true;
538 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
539 params->has_cpu_throttle_increment = true;
540 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
541 params->has_tls_creds = true;
542 params->tls_creds = g_strdup(s->parameters.tls_creds);
543 params->has_tls_hostname = true;
544 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
545 params->has_max_bandwidth = true;
546 params->max_bandwidth = s->parameters.max_bandwidth;
547 params->has_downtime_limit = true;
548 params->downtime_limit = s->parameters.downtime_limit;
549 params->has_x_checkpoint_delay = true;
550 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
551 params->has_block_incremental = true;
552 params->block_incremental = s->parameters.block_incremental;
553 params->has_x_multifd_channels = true;
554 params->x_multifd_channels = s->parameters.x_multifd_channels;
555 params->has_x_multifd_page_count = true;
556 params->x_multifd_page_count = s->parameters.x_multifd_page_count;
557 params->has_xbzrle_cache_size = true;
558 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
560 return params;
564 * Return true if we're already in the middle of a migration
565 * (i.e. any of the active or setup states)
567 static bool migration_is_setup_or_active(int state)
569 switch (state) {
570 case MIGRATION_STATUS_ACTIVE:
571 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
572 case MIGRATION_STATUS_SETUP:
573 case MIGRATION_STATUS_PRE_SWITCHOVER:
574 case MIGRATION_STATUS_DEVICE:
575 return true;
577 default:
578 return false;
583 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
585 info->has_ram = true;
586 info->ram = g_malloc0(sizeof(*info->ram));
587 info->ram->transferred = ram_counters.transferred;
588 info->ram->total = ram_bytes_total();
589 info->ram->duplicate = ram_counters.duplicate;
590 /* legacy value. It is not used anymore */
591 info->ram->skipped = 0;
592 info->ram->normal = ram_counters.normal;
593 info->ram->normal_bytes = ram_counters.normal *
594 qemu_target_page_size();
595 info->ram->mbps = s->mbps;
596 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
597 info->ram->postcopy_requests = ram_counters.postcopy_requests;
598 info->ram->page_size = qemu_target_page_size();
600 if (migrate_use_xbzrle()) {
601 info->has_xbzrle_cache = true;
602 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
603 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
604 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
605 info->xbzrle_cache->pages = xbzrle_counters.pages;
606 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
607 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
608 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
611 if (cpu_throttle_active()) {
612 info->has_cpu_throttle_percentage = true;
613 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
616 if (s->state != MIGRATION_STATUS_COMPLETED) {
617 info->ram->remaining = ram_bytes_remaining();
618 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
622 static void populate_disk_info(MigrationInfo *info)
624 if (blk_mig_active()) {
625 info->has_disk = true;
626 info->disk = g_malloc0(sizeof(*info->disk));
627 info->disk->transferred = blk_mig_bytes_transferred();
628 info->disk->remaining = blk_mig_bytes_remaining();
629 info->disk->total = blk_mig_bytes_total();
633 MigrationInfo *qmp_query_migrate(Error **errp)
635 MigrationInfo *info = g_malloc0(sizeof(*info));
636 MigrationState *s = migrate_get_current();
638 switch (s->state) {
639 case MIGRATION_STATUS_NONE:
640 /* no migration has happened ever */
641 break;
642 case MIGRATION_STATUS_SETUP:
643 info->has_status = true;
644 info->has_total_time = false;
645 break;
646 case MIGRATION_STATUS_ACTIVE:
647 case MIGRATION_STATUS_CANCELLING:
648 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
649 case MIGRATION_STATUS_PRE_SWITCHOVER:
650 case MIGRATION_STATUS_DEVICE:
651 /* TODO add some postcopy stats */
652 info->has_status = true;
653 info->has_total_time = true;
654 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
655 - s->start_time;
656 info->has_expected_downtime = true;
657 info->expected_downtime = s->expected_downtime;
658 info->has_setup_time = true;
659 info->setup_time = s->setup_time;
661 populate_ram_info(info, s);
662 populate_disk_info(info);
663 break;
664 case MIGRATION_STATUS_COLO:
665 info->has_status = true;
666 /* TODO: display COLO specific information (checkpoint info etc.) */
667 break;
668 case MIGRATION_STATUS_COMPLETED:
669 info->has_status = true;
670 info->has_total_time = true;
671 info->total_time = s->total_time;
672 info->has_downtime = true;
673 info->downtime = s->downtime;
674 info->has_setup_time = true;
675 info->setup_time = s->setup_time;
677 populate_ram_info(info, s);
678 break;
679 case MIGRATION_STATUS_FAILED:
680 info->has_status = true;
681 if (s->error) {
682 info->has_error_desc = true;
683 info->error_desc = g_strdup(error_get_pretty(s->error));
685 break;
686 case MIGRATION_STATUS_CANCELLED:
687 info->has_status = true;
688 break;
690 info->status = s->state;
692 return info;
696 * @migration_caps_check - check capability validity
698 * @cap_list: old capability list, array of bool
699 * @params: new capabilities to be applied soon
700 * @errp: set *errp if the check failed, with reason
702 * Returns true if check passed, otherwise false.
704 static bool migrate_caps_check(bool *cap_list,
705 MigrationCapabilityStatusList *params,
706 Error **errp)
708 MigrationCapabilityStatusList *cap;
709 bool old_postcopy_cap;
710 MigrationIncomingState *mis = migration_incoming_get_current();
712 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
714 for (cap = params; cap; cap = cap->next) {
715 cap_list[cap->value->capability] = cap->value->state;
718 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
719 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
720 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
721 "block migration");
722 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
723 return false;
725 #endif
727 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
728 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
729 /* The decompression threads asynchronously write into RAM
730 * rather than use the atomic copies needed to avoid
731 * userfaulting. It should be possible to fix the decompression
732 * threads for compatibility in future.
734 error_setg(errp, "Postcopy is not currently compatible "
735 "with compression");
736 return false;
739 /* This check is reasonably expensive, so only when it's being
740 * set the first time, also it's only the destination that needs
741 * special support.
743 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
744 !postcopy_ram_supported_by_host(mis)) {
745 /* postcopy_ram_supported_by_host will have emitted a more
746 * detailed message
748 error_setg(errp, "Postcopy is not supported");
749 return false;
753 return true;
756 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
757 Error **errp)
759 MigrationState *s = migrate_get_current();
760 MigrationCapabilityStatusList *cap;
761 bool cap_list[MIGRATION_CAPABILITY__MAX];
763 if (migration_is_setup_or_active(s->state)) {
764 error_setg(errp, QERR_MIGRATION_ACTIVE);
765 return;
768 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
769 if (!migrate_caps_check(cap_list, params, errp)) {
770 return;
773 for (cap = params; cap; cap = cap->next) {
774 s->enabled_capabilities[cap->value->capability] = cap->value->state;
779 * Check whether the parameters are valid. Error will be put into errp
780 * (if provided). Return true if valid, otherwise false.
782 static bool migrate_params_check(MigrationParameters *params, Error **errp)
784 if (params->has_compress_level &&
785 (params->compress_level > 9)) {
786 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
787 "is invalid, it should be in the range of 0 to 9");
788 return false;
791 if (params->has_compress_threads && (params->compress_threads < 1)) {
792 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
793 "compress_threads",
794 "is invalid, it should be in the range of 1 to 255");
795 return false;
798 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
799 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
800 "decompress_threads",
801 "is invalid, it should be in the range of 1 to 255");
802 return false;
805 if (params->has_cpu_throttle_initial &&
806 (params->cpu_throttle_initial < 1 ||
807 params->cpu_throttle_initial > 99)) {
808 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
809 "cpu_throttle_initial",
810 "an integer in the range of 1 to 99");
811 return false;
814 if (params->has_cpu_throttle_increment &&
815 (params->cpu_throttle_increment < 1 ||
816 params->cpu_throttle_increment > 99)) {
817 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
818 "cpu_throttle_increment",
819 "an integer in the range of 1 to 99");
820 return false;
823 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
824 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
825 " range of 0 to %zu bytes/second", SIZE_MAX);
826 return false;
829 if (params->has_downtime_limit &&
830 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
831 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
832 "the range of 0 to %d milliseconds",
833 MAX_MIGRATE_DOWNTIME);
834 return false;
837 /* x_checkpoint_delay is now always positive */
839 if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
840 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
841 "multifd_channels",
842 "is invalid, it should be in the range of 1 to 255");
843 return false;
845 if (params->has_x_multifd_page_count &&
846 (params->x_multifd_page_count < 1 ||
847 params->x_multifd_page_count > 10000)) {
848 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
849 "multifd_page_count",
850 "is invalid, it should be in the range of 1 to 10000");
851 return false;
854 if (params->has_xbzrle_cache_size &&
855 (params->xbzrle_cache_size < qemu_target_page_size() ||
856 !is_power_of_2(params->xbzrle_cache_size))) {
857 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
858 "xbzrle_cache_size",
859 "is invalid, it should be bigger than target page size"
860 " and a power of two");
861 return false;
864 return true;
867 static void migrate_params_test_apply(MigrateSetParameters *params,
868 MigrationParameters *dest)
870 *dest = migrate_get_current()->parameters;
872 /* TODO use QAPI_CLONE() instead of duplicating it inline */
874 if (params->has_compress_level) {
875 dest->compress_level = params->compress_level;
878 if (params->has_compress_threads) {
879 dest->compress_threads = params->compress_threads;
882 if (params->has_decompress_threads) {
883 dest->decompress_threads = params->decompress_threads;
886 if (params->has_cpu_throttle_initial) {
887 dest->cpu_throttle_initial = params->cpu_throttle_initial;
890 if (params->has_cpu_throttle_increment) {
891 dest->cpu_throttle_increment = params->cpu_throttle_increment;
894 if (params->has_tls_creds) {
895 assert(params->tls_creds->type == QTYPE_QSTRING);
896 dest->tls_creds = g_strdup(params->tls_creds->u.s);
899 if (params->has_tls_hostname) {
900 assert(params->tls_hostname->type == QTYPE_QSTRING);
901 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
904 if (params->has_max_bandwidth) {
905 dest->max_bandwidth = params->max_bandwidth;
908 if (params->has_downtime_limit) {
909 dest->downtime_limit = params->downtime_limit;
912 if (params->has_x_checkpoint_delay) {
913 dest->x_checkpoint_delay = params->x_checkpoint_delay;
916 if (params->has_block_incremental) {
917 dest->block_incremental = params->block_incremental;
919 if (params->has_x_multifd_channels) {
920 dest->x_multifd_channels = params->x_multifd_channels;
922 if (params->has_x_multifd_page_count) {
923 dest->x_multifd_page_count = params->x_multifd_page_count;
925 if (params->has_xbzrle_cache_size) {
926 dest->xbzrle_cache_size = params->xbzrle_cache_size;
930 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
932 MigrationState *s = migrate_get_current();
934 /* TODO use QAPI_CLONE() instead of duplicating it inline */
936 if (params->has_compress_level) {
937 s->parameters.compress_level = params->compress_level;
940 if (params->has_compress_threads) {
941 s->parameters.compress_threads = params->compress_threads;
944 if (params->has_decompress_threads) {
945 s->parameters.decompress_threads = params->decompress_threads;
948 if (params->has_cpu_throttle_initial) {
949 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
952 if (params->has_cpu_throttle_increment) {
953 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
956 if (params->has_tls_creds) {
957 g_free(s->parameters.tls_creds);
958 assert(params->tls_creds->type == QTYPE_QSTRING);
959 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
962 if (params->has_tls_hostname) {
963 g_free(s->parameters.tls_hostname);
964 assert(params->tls_hostname->type == QTYPE_QSTRING);
965 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
968 if (params->has_max_bandwidth) {
969 s->parameters.max_bandwidth = params->max_bandwidth;
970 if (s->to_dst_file) {
971 qemu_file_set_rate_limit(s->to_dst_file,
972 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
976 if (params->has_downtime_limit) {
977 s->parameters.downtime_limit = params->downtime_limit;
980 if (params->has_x_checkpoint_delay) {
981 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
982 if (migration_in_colo_state()) {
983 colo_checkpoint_notify(s);
987 if (params->has_block_incremental) {
988 s->parameters.block_incremental = params->block_incremental;
990 if (params->has_x_multifd_channels) {
991 s->parameters.x_multifd_channels = params->x_multifd_channels;
993 if (params->has_x_multifd_page_count) {
994 s->parameters.x_multifd_page_count = params->x_multifd_page_count;
996 if (params->has_xbzrle_cache_size) {
997 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
998 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1002 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1004 MigrationParameters tmp;
1006 /* TODO Rewrite "" to null instead */
1007 if (params->has_tls_creds
1008 && params->tls_creds->type == QTYPE_QNULL) {
1009 QDECREF(params->tls_creds->u.n);
1010 params->tls_creds->type = QTYPE_QSTRING;
1011 params->tls_creds->u.s = strdup("");
1013 /* TODO Rewrite "" to null instead */
1014 if (params->has_tls_hostname
1015 && params->tls_hostname->type == QTYPE_QNULL) {
1016 QDECREF(params->tls_hostname->u.n);
1017 params->tls_hostname->type = QTYPE_QSTRING;
1018 params->tls_hostname->u.s = strdup("");
1021 migrate_params_test_apply(params, &tmp);
1023 if (!migrate_params_check(&tmp, errp)) {
1024 /* Invalid parameter */
1025 return;
1028 migrate_params_apply(params, errp);
1032 void qmp_migrate_start_postcopy(Error **errp)
1034 MigrationState *s = migrate_get_current();
1036 if (!migrate_postcopy()) {
1037 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1038 " the start of migration");
1039 return;
1042 if (s->state == MIGRATION_STATUS_NONE) {
1043 error_setg(errp, "Postcopy must be started after migration has been"
1044 " started");
1045 return;
1048 * we don't error if migration has finished since that would be racy
1049 * with issuing this command.
1051 atomic_set(&s->start_postcopy, true);
1054 /* shared migration helpers */
1056 void migrate_set_state(int *state, int old_state, int new_state)
1058 assert(new_state < MIGRATION_STATUS__MAX);
1059 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1060 trace_migrate_set_state(MigrationStatus_str(new_state));
1061 migrate_generate_event(new_state);
1065 static MigrationCapabilityStatusList *migrate_cap_add(
1066 MigrationCapabilityStatusList *list,
1067 MigrationCapability index,
1068 bool state)
1070 MigrationCapabilityStatusList *cap;
1072 cap = g_new0(MigrationCapabilityStatusList, 1);
1073 cap->value = g_new0(MigrationCapabilityStatus, 1);
1074 cap->value->capability = index;
1075 cap->value->state = state;
1076 cap->next = list;
1078 return cap;
1081 void migrate_set_block_enabled(bool value, Error **errp)
1083 MigrationCapabilityStatusList *cap;
1085 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1086 qmp_migrate_set_capabilities(cap, errp);
1087 qapi_free_MigrationCapabilityStatusList(cap);
1090 static void migrate_set_block_incremental(MigrationState *s, bool value)
1092 s->parameters.block_incremental = value;
1095 static void block_cleanup_parameters(MigrationState *s)
1097 if (s->must_remove_block_options) {
1098 /* setting to false can never fail */
1099 migrate_set_block_enabled(false, &error_abort);
1100 migrate_set_block_incremental(s, false);
1101 s->must_remove_block_options = false;
1105 static void migrate_fd_cleanup(void *opaque)
1107 MigrationState *s = opaque;
1109 qemu_bh_delete(s->cleanup_bh);
1110 s->cleanup_bh = NULL;
1112 qemu_savevm_state_cleanup();
1114 if (s->to_dst_file) {
1115 Error *local_err = NULL;
1117 trace_migrate_fd_cleanup();
1118 qemu_mutex_unlock_iothread();
1119 if (s->migration_thread_running) {
1120 qemu_thread_join(&s->thread);
1121 s->migration_thread_running = false;
1123 qemu_mutex_lock_iothread();
1125 if (multifd_save_cleanup(&local_err) != 0) {
1126 error_report_err(local_err);
1128 qemu_fclose(s->to_dst_file);
1129 s->to_dst_file = NULL;
1132 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1133 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
1135 if (s->state == MIGRATION_STATUS_CANCELLING) {
1136 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1137 MIGRATION_STATUS_CANCELLED);
1140 if (s->error) {
1141 /* It is used on info migrate. We can't free it */
1142 error_report_err(error_copy(s->error));
1144 notifier_list_notify(&migration_state_notifiers, s);
1145 block_cleanup_parameters(s);
1148 void migrate_set_error(MigrationState *s, const Error *error)
1150 qemu_mutex_lock(&s->error_mutex);
1151 if (!s->error) {
1152 s->error = error_copy(error);
1154 qemu_mutex_unlock(&s->error_mutex);
1157 void migrate_fd_error(MigrationState *s, const Error *error)
1159 trace_migrate_fd_error(error_get_pretty(error));
1160 assert(s->to_dst_file == NULL);
1161 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1162 MIGRATION_STATUS_FAILED);
1163 migrate_set_error(s, error);
1166 static void migrate_fd_cancel(MigrationState *s)
1168 int old_state ;
1169 QEMUFile *f = migrate_get_current()->to_dst_file;
1170 trace_migrate_fd_cancel();
1172 if (s->rp_state.from_dst_file) {
1173 /* shutdown the rp socket, so causing the rp thread to shutdown */
1174 qemu_file_shutdown(s->rp_state.from_dst_file);
1177 do {
1178 old_state = s->state;
1179 if (!migration_is_setup_or_active(old_state)) {
1180 break;
1182 /* If the migration is paused, kick it out of the pause */
1183 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1184 qemu_sem_post(&s->pause_sem);
1186 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1187 } while (s->state != MIGRATION_STATUS_CANCELLING);
1190 * If we're unlucky the migration code might be stuck somewhere in a
1191 * send/write while the network has failed and is waiting to timeout;
1192 * if we've got shutdown(2) available then we can force it to quit.
1193 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1194 * called in a bh, so there is no race against this cancel.
1196 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1197 qemu_file_shutdown(f);
1199 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1200 Error *local_err = NULL;
1202 bdrv_invalidate_cache_all(&local_err);
1203 if (local_err) {
1204 error_report_err(local_err);
1205 } else {
1206 s->block_inactive = false;
1211 void add_migration_state_change_notifier(Notifier *notify)
1213 notifier_list_add(&migration_state_notifiers, notify);
1216 void remove_migration_state_change_notifier(Notifier *notify)
1218 notifier_remove(notify);
1221 bool migration_in_setup(MigrationState *s)
1223 return s->state == MIGRATION_STATUS_SETUP;
1226 bool migration_has_finished(MigrationState *s)
1228 return s->state == MIGRATION_STATUS_COMPLETED;
1231 bool migration_has_failed(MigrationState *s)
1233 return (s->state == MIGRATION_STATUS_CANCELLED ||
1234 s->state == MIGRATION_STATUS_FAILED);
1237 bool migration_in_postcopy(void)
1239 MigrationState *s = migrate_get_current();
1241 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1244 bool migration_in_postcopy_after_devices(MigrationState *s)
1246 return migration_in_postcopy() && s->postcopy_after_devices;
1249 bool migration_is_idle(void)
1251 MigrationState *s = migrate_get_current();
1253 switch (s->state) {
1254 case MIGRATION_STATUS_NONE:
1255 case MIGRATION_STATUS_CANCELLED:
1256 case MIGRATION_STATUS_COMPLETED:
1257 case MIGRATION_STATUS_FAILED:
1258 return true;
1259 case MIGRATION_STATUS_SETUP:
1260 case MIGRATION_STATUS_CANCELLING:
1261 case MIGRATION_STATUS_ACTIVE:
1262 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1263 case MIGRATION_STATUS_COLO:
1264 case MIGRATION_STATUS_PRE_SWITCHOVER:
1265 case MIGRATION_STATUS_DEVICE:
1266 return false;
1267 case MIGRATION_STATUS__MAX:
1268 g_assert_not_reached();
1271 return false;
1274 void migrate_init(MigrationState *s)
1277 * Reinitialise all migration state, except
1278 * parameters/capabilities that the user set, and
1279 * locks.
1281 s->bytes_xfer = 0;
1282 s->xfer_limit = 0;
1283 s->cleanup_bh = 0;
1284 s->to_dst_file = NULL;
1285 s->state = MIGRATION_STATUS_NONE;
1286 s->rp_state.from_dst_file = NULL;
1287 s->rp_state.error = false;
1288 s->mbps = 0.0;
1289 s->downtime = 0;
1290 s->expected_downtime = 0;
1291 s->setup_time = 0;
1292 s->start_postcopy = false;
1293 s->postcopy_after_devices = false;
1294 s->migration_thread_running = false;
1295 error_free(s->error);
1296 s->error = NULL;
1298 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1300 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1301 s->total_time = 0;
1302 s->vm_was_running = false;
1303 s->iteration_initial_bytes = 0;
1304 s->threshold_size = 0;
1307 static GSList *migration_blockers;
1309 int migrate_add_blocker(Error *reason, Error **errp)
1311 if (migrate_get_current()->only_migratable) {
1312 error_propagate(errp, error_copy(reason));
1313 error_prepend(errp, "disallowing migration blocker "
1314 "(--only_migratable) for: ");
1315 return -EACCES;
1318 if (migration_is_idle()) {
1319 migration_blockers = g_slist_prepend(migration_blockers, reason);
1320 return 0;
1323 error_propagate(errp, error_copy(reason));
1324 error_prepend(errp, "disallowing migration blocker (migration in "
1325 "progress) for: ");
1326 return -EBUSY;
1329 void migrate_del_blocker(Error *reason)
1331 migration_blockers = g_slist_remove(migration_blockers, reason);
1334 void qmp_migrate_incoming(const char *uri, Error **errp)
1336 Error *local_err = NULL;
1337 static bool once = true;
1339 if (!deferred_incoming) {
1340 error_setg(errp, "For use with '-incoming defer'");
1341 return;
1343 if (!once) {
1344 error_setg(errp, "The incoming migration has already been started");
1347 qemu_start_incoming_migration(uri, &local_err);
1349 if (local_err) {
1350 error_propagate(errp, local_err);
1351 return;
1354 once = false;
1357 bool migration_is_blocked(Error **errp)
1359 if (qemu_savevm_state_blocked(errp)) {
1360 return true;
1363 if (migration_blockers) {
1364 error_propagate(errp, error_copy(migration_blockers->data));
1365 return true;
1368 return false;
1371 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1372 bool has_inc, bool inc, bool has_detach, bool detach,
1373 Error **errp)
1375 Error *local_err = NULL;
1376 MigrationState *s = migrate_get_current();
1377 const char *p;
1379 if (migration_is_setup_or_active(s->state) ||
1380 s->state == MIGRATION_STATUS_CANCELLING ||
1381 s->state == MIGRATION_STATUS_COLO) {
1382 error_setg(errp, QERR_MIGRATION_ACTIVE);
1383 return;
1385 if (runstate_check(RUN_STATE_INMIGRATE)) {
1386 error_setg(errp, "Guest is waiting for an incoming migration");
1387 return;
1390 if (migration_is_blocked(errp)) {
1391 return;
1394 if ((has_blk && blk) || (has_inc && inc)) {
1395 if (migrate_use_block() || migrate_use_block_incremental()) {
1396 error_setg(errp, "Command options are incompatible with "
1397 "current migration capabilities");
1398 return;
1400 migrate_set_block_enabled(true, &local_err);
1401 if (local_err) {
1402 error_propagate(errp, local_err);
1403 return;
1405 s->must_remove_block_options = true;
1408 if (has_inc && inc) {
1409 migrate_set_block_incremental(s, true);
1412 migrate_init(s);
1414 if (strstart(uri, "tcp:", &p)) {
1415 tcp_start_outgoing_migration(s, p, &local_err);
1416 #ifdef CONFIG_RDMA
1417 } else if (strstart(uri, "rdma:", &p)) {
1418 rdma_start_outgoing_migration(s, p, &local_err);
1419 #endif
1420 } else if (strstart(uri, "exec:", &p)) {
1421 exec_start_outgoing_migration(s, p, &local_err);
1422 } else if (strstart(uri, "unix:", &p)) {
1423 unix_start_outgoing_migration(s, p, &local_err);
1424 } else if (strstart(uri, "fd:", &p)) {
1425 fd_start_outgoing_migration(s, p, &local_err);
1426 } else {
1427 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1428 "a valid migration protocol");
1429 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1430 MIGRATION_STATUS_FAILED);
1431 return;
1434 if (local_err) {
1435 migrate_fd_error(s, local_err);
1436 error_propagate(errp, local_err);
1437 return;
1441 void qmp_migrate_cancel(Error **errp)
1443 migrate_fd_cancel(migrate_get_current());
1446 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1448 MigrationState *s = migrate_get_current();
1449 if (s->state != state) {
1450 error_setg(errp, "Migration not in expected state: %s",
1451 MigrationStatus_str(s->state));
1452 return;
1454 qemu_sem_post(&s->pause_sem);
1457 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1459 MigrateSetParameters p = {
1460 .has_xbzrle_cache_size = true,
1461 .xbzrle_cache_size = value,
1464 qmp_migrate_set_parameters(&p, errp);
1467 int64_t qmp_query_migrate_cache_size(Error **errp)
1469 return migrate_xbzrle_cache_size();
1472 void qmp_migrate_set_speed(int64_t value, Error **errp)
1474 MigrateSetParameters p = {
1475 .has_max_bandwidth = true,
1476 .max_bandwidth = value,
1479 qmp_migrate_set_parameters(&p, errp);
1482 void qmp_migrate_set_downtime(double value, Error **errp)
1484 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1485 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1486 "the range of 0 to %d seconds",
1487 MAX_MIGRATE_DOWNTIME_SECONDS);
1488 return;
1491 value *= 1000; /* Convert to milliseconds */
1492 value = MAX(0, MIN(INT64_MAX, value));
1494 MigrateSetParameters p = {
1495 .has_downtime_limit = true,
1496 .downtime_limit = value,
1499 qmp_migrate_set_parameters(&p, errp);
1502 bool migrate_release_ram(void)
1504 MigrationState *s;
1506 s = migrate_get_current();
1508 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1511 bool migrate_postcopy_ram(void)
1513 MigrationState *s;
1515 s = migrate_get_current();
1517 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1520 bool migrate_postcopy(void)
1522 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1525 bool migrate_auto_converge(void)
1527 MigrationState *s;
1529 s = migrate_get_current();
1531 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1534 bool migrate_zero_blocks(void)
1536 MigrationState *s;
1538 s = migrate_get_current();
1540 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1543 bool migrate_use_compression(void)
1545 MigrationState *s;
1547 s = migrate_get_current();
1549 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1552 int migrate_compress_level(void)
1554 MigrationState *s;
1556 s = migrate_get_current();
1558 return s->parameters.compress_level;
1561 int migrate_compress_threads(void)
1563 MigrationState *s;
1565 s = migrate_get_current();
1567 return s->parameters.compress_threads;
1570 int migrate_decompress_threads(void)
1572 MigrationState *s;
1574 s = migrate_get_current();
1576 return s->parameters.decompress_threads;
1579 bool migrate_dirty_bitmaps(void)
1581 MigrationState *s;
1583 s = migrate_get_current();
1585 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1588 bool migrate_use_events(void)
1590 MigrationState *s;
1592 s = migrate_get_current();
1594 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1597 bool migrate_use_multifd(void)
1599 MigrationState *s;
1601 s = migrate_get_current();
1603 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1606 bool migrate_pause_before_switchover(void)
1608 MigrationState *s;
1610 s = migrate_get_current();
1612 return s->enabled_capabilities[
1613 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1616 int migrate_multifd_channels(void)
1618 MigrationState *s;
1620 s = migrate_get_current();
1622 return s->parameters.x_multifd_channels;
1625 int migrate_multifd_page_count(void)
1627 MigrationState *s;
1629 s = migrate_get_current();
1631 return s->parameters.x_multifd_page_count;
1634 int migrate_use_xbzrle(void)
1636 MigrationState *s;
1638 s = migrate_get_current();
1640 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1643 int64_t migrate_xbzrle_cache_size(void)
1645 MigrationState *s;
1647 s = migrate_get_current();
1649 return s->parameters.xbzrle_cache_size;
1652 bool migrate_use_block(void)
1654 MigrationState *s;
1656 s = migrate_get_current();
1658 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
1661 bool migrate_use_return_path(void)
1663 MigrationState *s;
1665 s = migrate_get_current();
1667 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
1670 bool migrate_use_block_incremental(void)
1672 MigrationState *s;
1674 s = migrate_get_current();
1676 return s->parameters.block_incremental;
1679 /* migration thread support */
1681 * Something bad happened to the RP stream, mark an error
1682 * The caller shall print or trace something to indicate why
1684 static void mark_source_rp_bad(MigrationState *s)
1686 s->rp_state.error = true;
1689 static struct rp_cmd_args {
1690 ssize_t len; /* -1 = variable */
1691 const char *name;
1692 } rp_cmd_args[] = {
1693 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1694 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1695 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1696 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1697 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1698 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1702 * Process a request for pages received on the return path,
1703 * We're allowed to send more than requested (e.g. to round to our page size)
1704 * and we don't need to send pages that have already been sent.
1706 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1707 ram_addr_t start, size_t len)
1709 long our_host_ps = getpagesize();
1711 trace_migrate_handle_rp_req_pages(rbname, start, len);
1714 * Since we currently insist on matching page sizes, just sanity check
1715 * we're being asked for whole host pages.
1717 if (start & (our_host_ps-1) ||
1718 (len & (our_host_ps-1))) {
1719 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1720 " len: %zd", __func__, start, len);
1721 mark_source_rp_bad(ms);
1722 return;
1725 if (ram_save_queue_pages(rbname, start, len)) {
1726 mark_source_rp_bad(ms);
1731 * Handles messages sent on the return path towards the source VM
1734 static void *source_return_path_thread(void *opaque)
1736 MigrationState *ms = opaque;
1737 QEMUFile *rp = ms->rp_state.from_dst_file;
1738 uint16_t header_len, header_type;
1739 uint8_t buf[512];
1740 uint32_t tmp32, sibling_error;
1741 ram_addr_t start = 0; /* =0 to silence warning */
1742 size_t len = 0, expected_len;
1743 int res;
1745 trace_source_return_path_thread_entry();
1746 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1747 migration_is_setup_or_active(ms->state)) {
1748 trace_source_return_path_thread_loop_top();
1749 header_type = qemu_get_be16(rp);
1750 header_len = qemu_get_be16(rp);
1752 if (qemu_file_get_error(rp)) {
1753 mark_source_rp_bad(ms);
1754 goto out;
1757 if (header_type >= MIG_RP_MSG_MAX ||
1758 header_type == MIG_RP_MSG_INVALID) {
1759 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1760 header_type, header_len);
1761 mark_source_rp_bad(ms);
1762 goto out;
1765 if ((rp_cmd_args[header_type].len != -1 &&
1766 header_len != rp_cmd_args[header_type].len) ||
1767 header_len > sizeof(buf)) {
1768 error_report("RP: Received '%s' message (0x%04x) with"
1769 "incorrect length %d expecting %zu",
1770 rp_cmd_args[header_type].name, header_type, header_len,
1771 (size_t)rp_cmd_args[header_type].len);
1772 mark_source_rp_bad(ms);
1773 goto out;
1776 /* We know we've got a valid header by this point */
1777 res = qemu_get_buffer(rp, buf, header_len);
1778 if (res != header_len) {
1779 error_report("RP: Failed reading data for message 0x%04x"
1780 " read %d expected %d",
1781 header_type, res, header_len);
1782 mark_source_rp_bad(ms);
1783 goto out;
1786 /* OK, we have the message and the data */
1787 switch (header_type) {
1788 case MIG_RP_MSG_SHUT:
1789 sibling_error = ldl_be_p(buf);
1790 trace_source_return_path_thread_shut(sibling_error);
1791 if (sibling_error) {
1792 error_report("RP: Sibling indicated error %d", sibling_error);
1793 mark_source_rp_bad(ms);
1796 * We'll let the main thread deal with closing the RP
1797 * we could do a shutdown(2) on it, but we're the only user
1798 * anyway, so there's nothing gained.
1800 goto out;
1802 case MIG_RP_MSG_PONG:
1803 tmp32 = ldl_be_p(buf);
1804 trace_source_return_path_thread_pong(tmp32);
1805 break;
1807 case MIG_RP_MSG_REQ_PAGES:
1808 start = ldq_be_p(buf);
1809 len = ldl_be_p(buf + 8);
1810 migrate_handle_rp_req_pages(ms, NULL, start, len);
1811 break;
1813 case MIG_RP_MSG_REQ_PAGES_ID:
1814 expected_len = 12 + 1; /* header + termination */
1816 if (header_len >= expected_len) {
1817 start = ldq_be_p(buf);
1818 len = ldl_be_p(buf + 8);
1819 /* Now we expect an idstr */
1820 tmp32 = buf[12]; /* Length of the following idstr */
1821 buf[13 + tmp32] = '\0';
1822 expected_len += tmp32;
1824 if (header_len != expected_len) {
1825 error_report("RP: Req_Page_id with length %d expecting %zd",
1826 header_len, expected_len);
1827 mark_source_rp_bad(ms);
1828 goto out;
1830 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1831 break;
1833 default:
1834 break;
1837 if (qemu_file_get_error(rp)) {
1838 trace_source_return_path_thread_bad_end();
1839 mark_source_rp_bad(ms);
1842 trace_source_return_path_thread_end();
1843 out:
1844 ms->rp_state.from_dst_file = NULL;
1845 qemu_fclose(rp);
1846 return NULL;
1849 static int open_return_path_on_source(MigrationState *ms)
1852 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
1853 if (!ms->rp_state.from_dst_file) {
1854 return -1;
1857 trace_open_return_path_on_source();
1858 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1859 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1861 trace_open_return_path_on_source_continue();
1863 return 0;
1866 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1867 static int await_return_path_close_on_source(MigrationState *ms)
1870 * If this is a normal exit then the destination will send a SHUT and the
1871 * rp_thread will exit, however if there's an error we need to cause
1872 * it to exit.
1874 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
1876 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1877 * waiting for the destination.
1879 qemu_file_shutdown(ms->rp_state.from_dst_file);
1880 mark_source_rp_bad(ms);
1882 trace_await_return_path_close_on_source_joining();
1883 qemu_thread_join(&ms->rp_state.rp_thread);
1884 trace_await_return_path_close_on_source_close();
1885 return ms->rp_state.error;
1889 * Switch from normal iteration to postcopy
1890 * Returns non-0 on error
1892 static int postcopy_start(MigrationState *ms)
1894 int ret;
1895 QIOChannelBuffer *bioc;
1896 QEMUFile *fb;
1897 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1898 bool restart_block = false;
1899 int cur_state = MIGRATION_STATUS_ACTIVE;
1900 if (!migrate_pause_before_switchover()) {
1901 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1902 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1905 trace_postcopy_start();
1906 qemu_mutex_lock_iothread();
1907 trace_postcopy_start_set_run();
1909 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1910 global_state_store();
1911 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1912 if (ret < 0) {
1913 goto fail;
1916 ret = migration_maybe_pause(ms, &cur_state,
1917 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1918 if (ret < 0) {
1919 goto fail;
1922 ret = bdrv_inactivate_all();
1923 if (ret < 0) {
1924 goto fail;
1926 restart_block = true;
1929 * Cause any non-postcopiable, but iterative devices to
1930 * send out their final data.
1932 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1935 * in Finish migrate and with the io-lock held everything should
1936 * be quiet, but we've potentially still got dirty pages and we
1937 * need to tell the destination to throw any pages it's already received
1938 * that are dirty
1940 if (migrate_postcopy_ram()) {
1941 if (ram_postcopy_send_discard_bitmap(ms)) {
1942 error_report("postcopy send discard bitmap failed");
1943 goto fail;
1948 * send rest of state - note things that are doing postcopy
1949 * will notice we're in POSTCOPY_ACTIVE and not actually
1950 * wrap their state up here
1952 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
1953 if (migrate_postcopy_ram()) {
1954 /* Ping just for debugging, helps line traces up */
1955 qemu_savevm_send_ping(ms->to_dst_file, 2);
1959 * While loading the device state we may trigger page transfer
1960 * requests and the fd must be free to process those, and thus
1961 * the destination must read the whole device state off the fd before
1962 * it starts processing it. Unfortunately the ad-hoc migration format
1963 * doesn't allow the destination to know the size to read without fully
1964 * parsing it through each devices load-state code (especially the open
1965 * coded devices that use get/put).
1966 * So we wrap the device state up in a package with a length at the start;
1967 * to do this we use a qemu_buf to hold the whole of the device state.
1969 bioc = qio_channel_buffer_new(4096);
1970 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
1971 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
1972 object_unref(OBJECT(bioc));
1975 * Make sure the receiver can get incoming pages before we send the rest
1976 * of the state
1978 qemu_savevm_send_postcopy_listen(fb);
1980 qemu_savevm_state_complete_precopy(fb, false, false);
1981 if (migrate_postcopy_ram()) {
1982 qemu_savevm_send_ping(fb, 3);
1985 qemu_savevm_send_postcopy_run(fb);
1987 /* <><> end of stuff going into the package */
1989 /* Last point of recovery; as soon as we send the package the destination
1990 * can open devices and potentially start running.
1991 * Lets just check again we've not got any errors.
1993 ret = qemu_file_get_error(ms->to_dst_file);
1994 if (ret) {
1995 error_report("postcopy_start: Migration stream errored (pre package)");
1996 goto fail_closefb;
1999 restart_block = false;
2001 /* Now send that blob */
2002 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2003 goto fail_closefb;
2005 qemu_fclose(fb);
2007 /* Send a notify to give a chance for anything that needs to happen
2008 * at the transition to postcopy and after the device state; in particular
2009 * spice needs to trigger a transition now
2011 ms->postcopy_after_devices = true;
2012 notifier_list_notify(&migration_state_notifiers, ms);
2014 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2016 qemu_mutex_unlock_iothread();
2018 if (migrate_postcopy_ram()) {
2020 * Although this ping is just for debug, it could potentially be
2021 * used for getting a better measurement of downtime at the source.
2023 qemu_savevm_send_ping(ms->to_dst_file, 4);
2026 if (migrate_release_ram()) {
2027 ram_postcopy_migrated_memory_release(ms);
2030 ret = qemu_file_get_error(ms->to_dst_file);
2031 if (ret) {
2032 error_report("postcopy_start: Migration stream errored");
2033 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2034 MIGRATION_STATUS_FAILED);
2037 return ret;
2039 fail_closefb:
2040 qemu_fclose(fb);
2041 fail:
2042 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2043 MIGRATION_STATUS_FAILED);
2044 if (restart_block) {
2045 /* A failure happened early enough that we know the destination hasn't
2046 * accessed block devices, so we're safe to recover.
2048 Error *local_err = NULL;
2050 bdrv_invalidate_cache_all(&local_err);
2051 if (local_err) {
2052 error_report_err(local_err);
2055 qemu_mutex_unlock_iothread();
2056 return -1;
2060 * migration_maybe_pause: Pause if required to by
2061 * migrate_pause_before_switchover called with the iothread locked
2062 * Returns: 0 on success
2064 static int migration_maybe_pause(MigrationState *s,
2065 int *current_active_state,
2066 int new_state)
2068 if (!migrate_pause_before_switchover()) {
2069 return 0;
2072 /* Since leaving this state is not atomic with posting the semaphore
2073 * it's possible that someone could have issued multiple migrate_continue
2074 * and the semaphore is incorrectly positive at this point;
2075 * the docs say it's undefined to reinit a semaphore that's already
2076 * init'd, so use timedwait to eat up any existing posts.
2078 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2079 /* This block intentionally left blank */
2082 qemu_mutex_unlock_iothread();
2083 migrate_set_state(&s->state, *current_active_state,
2084 MIGRATION_STATUS_PRE_SWITCHOVER);
2085 qemu_sem_wait(&s->pause_sem);
2086 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2087 new_state);
2088 *current_active_state = new_state;
2089 qemu_mutex_lock_iothread();
2091 return s->state == new_state ? 0 : -EINVAL;
2095 * migration_completion: Used by migration_thread when there's not much left.
2096 * The caller 'breaks' the loop when this returns.
2098 * @s: Current migration state
2100 static void migration_completion(MigrationState *s)
2102 int ret;
2103 int current_active_state = s->state;
2105 if (s->state == MIGRATION_STATUS_ACTIVE) {
2106 qemu_mutex_lock_iothread();
2107 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2108 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2109 s->vm_was_running = runstate_is_running();
2110 ret = global_state_store();
2112 if (!ret) {
2113 bool inactivate = !migrate_colo_enabled();
2114 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2115 if (ret >= 0) {
2116 ret = migration_maybe_pause(s, &current_active_state,
2117 MIGRATION_STATUS_DEVICE);
2119 if (ret >= 0) {
2120 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2121 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2122 inactivate);
2124 if (inactivate && ret >= 0) {
2125 s->block_inactive = true;
2128 qemu_mutex_unlock_iothread();
2130 if (ret < 0) {
2131 goto fail;
2133 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2134 trace_migration_completion_postcopy_end();
2136 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2137 trace_migration_completion_postcopy_end_after_complete();
2141 * If rp was opened we must clean up the thread before
2142 * cleaning everything else up (since if there are no failures
2143 * it will wait for the destination to send it's status in
2144 * a SHUT command).
2146 if (s->rp_state.from_dst_file) {
2147 int rp_error;
2148 trace_migration_return_path_end_before();
2149 rp_error = await_return_path_close_on_source(s);
2150 trace_migration_return_path_end_after(rp_error);
2151 if (rp_error) {
2152 goto fail_invalidate;
2156 if (qemu_file_get_error(s->to_dst_file)) {
2157 trace_migration_completion_file_err();
2158 goto fail_invalidate;
2161 if (!migrate_colo_enabled()) {
2162 migrate_set_state(&s->state, current_active_state,
2163 MIGRATION_STATUS_COMPLETED);
2166 return;
2168 fail_invalidate:
2169 /* If not doing postcopy, vm_start() will be called: let's regain
2170 * control on images.
2172 if (s->state == MIGRATION_STATUS_ACTIVE ||
2173 s->state == MIGRATION_STATUS_DEVICE) {
2174 Error *local_err = NULL;
2176 qemu_mutex_lock_iothread();
2177 bdrv_invalidate_cache_all(&local_err);
2178 if (local_err) {
2179 error_report_err(local_err);
2180 } else {
2181 s->block_inactive = false;
2183 qemu_mutex_unlock_iothread();
2186 fail:
2187 migrate_set_state(&s->state, current_active_state,
2188 MIGRATION_STATUS_FAILED);
2191 bool migrate_colo_enabled(void)
2193 MigrationState *s = migrate_get_current();
2194 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2197 static void migration_calculate_complete(MigrationState *s)
2199 uint64_t bytes = qemu_ftell(s->to_dst_file);
2200 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2202 s->total_time = end_time - s->start_time;
2203 if (!s->downtime) {
2205 * It's still not set, so we are precopy migration. For
2206 * postcopy, downtime is calculated during postcopy_start().
2208 s->downtime = end_time - s->downtime_start;
2211 if (s->total_time) {
2212 s->mbps = ((double) bytes * 8.0) / s->total_time / 1000;
2216 static void migration_update_counters(MigrationState *s,
2217 int64_t current_time)
2219 uint64_t transferred, time_spent;
2220 double bandwidth;
2222 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2223 return;
2226 transferred = qemu_ftell(s->to_dst_file) - s->iteration_initial_bytes;
2227 time_spent = current_time - s->iteration_start_time;
2228 bandwidth = (double)transferred / time_spent;
2229 s->threshold_size = bandwidth * s->parameters.downtime_limit;
2231 s->mbps = (((double) transferred * 8.0) /
2232 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2235 * if we haven't sent anything, we don't want to
2236 * recalculate. 10000 is a small enough number for our purposes
2238 if (ram_counters.dirty_pages_rate && transferred > 10000) {
2239 s->expected_downtime = ram_counters.dirty_pages_rate *
2240 qemu_target_page_size() / bandwidth;
2243 qemu_file_reset_rate_limit(s->to_dst_file);
2245 s->iteration_start_time = current_time;
2246 s->iteration_initial_bytes = qemu_ftell(s->to_dst_file);
2248 trace_migrate_transferred(transferred, time_spent,
2249 bandwidth, s->threshold_size);
2252 /* Migration thread iteration status */
2253 typedef enum {
2254 MIG_ITERATE_RESUME, /* Resume current iteration */
2255 MIG_ITERATE_SKIP, /* Skip current iteration */
2256 MIG_ITERATE_BREAK, /* Break the loop */
2257 } MigIterateState;
2260 * Return true if continue to the next iteration directly, false
2261 * otherwise.
2263 static MigIterateState migration_iteration_run(MigrationState *s)
2265 uint64_t pending_size, pend_pre, pend_compat, pend_post;
2266 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2268 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2269 &pend_compat, &pend_post);
2270 pending_size = pend_pre + pend_compat + pend_post;
2272 trace_migrate_pending(pending_size, s->threshold_size,
2273 pend_pre, pend_compat, pend_post);
2275 if (pending_size && pending_size >= s->threshold_size) {
2276 /* Still a significant amount to transfer */
2277 if (migrate_postcopy() && !in_postcopy &&
2278 pend_pre <= s->threshold_size &&
2279 atomic_read(&s->start_postcopy)) {
2280 if (postcopy_start(s)) {
2281 error_report("%s: postcopy failed to start", __func__);
2283 return MIG_ITERATE_SKIP;
2285 /* Just another iteration step */
2286 qemu_savevm_state_iterate(s->to_dst_file,
2287 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2288 } else {
2289 trace_migration_thread_low_pending(pending_size);
2290 migration_completion(s);
2291 return MIG_ITERATE_BREAK;
2294 return MIG_ITERATE_RESUME;
2297 static void migration_iteration_finish(MigrationState *s)
2299 /* If we enabled cpu throttling for auto-converge, turn it off. */
2300 cpu_throttle_stop();
2302 qemu_mutex_lock_iothread();
2303 switch (s->state) {
2304 case MIGRATION_STATUS_COMPLETED:
2305 migration_calculate_complete(s);
2306 runstate_set(RUN_STATE_POSTMIGRATE);
2307 break;
2309 case MIGRATION_STATUS_ACTIVE:
2311 * We should really assert here, but since it's during
2312 * migration, let's try to reduce the usage of assertions.
2314 if (!migrate_colo_enabled()) {
2315 error_report("%s: critical error: calling COLO code without "
2316 "COLO enabled", __func__);
2318 migrate_start_colo_process(s);
2320 * Fixme: we will run VM in COLO no matter its old running state.
2321 * After exited COLO, we will keep running.
2323 s->vm_was_running = true;
2324 /* Fallthrough */
2325 case MIGRATION_STATUS_FAILED:
2326 case MIGRATION_STATUS_CANCELLED:
2327 if (s->vm_was_running) {
2328 vm_start();
2329 } else {
2330 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2331 runstate_set(RUN_STATE_POSTMIGRATE);
2334 break;
2336 default:
2337 /* Should not reach here, but if so, forgive the VM. */
2338 error_report("%s: Unknown ending state %d", __func__, s->state);
2339 break;
2341 qemu_bh_schedule(s->cleanup_bh);
2342 qemu_mutex_unlock_iothread();
2346 * Master migration thread on the source VM.
2347 * It drives the migration and pumps the data down the outgoing channel.
2349 static void *migration_thread(void *opaque)
2351 MigrationState *s = opaque;
2352 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2354 rcu_register_thread();
2356 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2358 qemu_savevm_state_header(s->to_dst_file);
2361 * If we opened the return path, we need to make sure dst has it
2362 * opened as well.
2364 if (s->rp_state.from_dst_file) {
2365 /* Now tell the dest that it should open its end so it can reply */
2366 qemu_savevm_send_open_return_path(s->to_dst_file);
2368 /* And do a ping that will make stuff easier to debug */
2369 qemu_savevm_send_ping(s->to_dst_file, 1);
2372 if (migrate_postcopy()) {
2374 * Tell the destination that we *might* want to do postcopy later;
2375 * if the other end can't do postcopy it should fail now, nice and
2376 * early.
2378 qemu_savevm_send_postcopy_advise(s->to_dst_file);
2381 qemu_savevm_state_setup(s->to_dst_file);
2383 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
2384 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2385 MIGRATION_STATUS_ACTIVE);
2387 trace_migration_thread_setup_complete();
2389 while (s->state == MIGRATION_STATUS_ACTIVE ||
2390 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2391 int64_t current_time;
2393 if (!qemu_file_rate_limit(s->to_dst_file)) {
2394 MigIterateState iter_state = migration_iteration_run(s);
2395 if (iter_state == MIG_ITERATE_SKIP) {
2396 continue;
2397 } else if (iter_state == MIG_ITERATE_BREAK) {
2398 break;
2402 if (qemu_file_get_error(s->to_dst_file)) {
2403 if (migration_is_setup_or_active(s->state)) {
2404 migrate_set_state(&s->state, s->state,
2405 MIGRATION_STATUS_FAILED);
2407 trace_migration_thread_file_err();
2408 break;
2411 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2413 migration_update_counters(s, current_time);
2415 if (qemu_file_rate_limit(s->to_dst_file)) {
2416 /* usleep expects microseconds */
2417 g_usleep((s->iteration_start_time + BUFFER_DELAY -
2418 current_time) * 1000);
2422 trace_migration_thread_after_loop();
2423 migration_iteration_finish(s);
2424 rcu_unregister_thread();
2425 return NULL;
2428 void migrate_fd_connect(MigrationState *s, Error *error_in)
2430 s->expected_downtime = s->parameters.downtime_limit;
2431 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
2432 if (error_in) {
2433 migrate_fd_error(s, error_in);
2434 migrate_fd_cleanup(s);
2435 return;
2438 qemu_file_set_blocking(s->to_dst_file, true);
2439 qemu_file_set_rate_limit(s->to_dst_file,
2440 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
2442 /* Notify before starting migration thread */
2443 notifier_list_notify(&migration_state_notifiers, s);
2446 * Open the return path. For postcopy, it is used exclusively. For
2447 * precopy, only if user specified "return-path" capability would
2448 * QEMU uses the return path.
2450 if (migrate_postcopy_ram() || migrate_use_return_path()) {
2451 if (open_return_path_on_source(s)) {
2452 error_report("Unable to open return-path for postcopy");
2453 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2454 MIGRATION_STATUS_FAILED);
2455 migrate_fd_cleanup(s);
2456 return;
2460 if (multifd_save_setup() != 0) {
2461 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2462 MIGRATION_STATUS_FAILED);
2463 migrate_fd_cleanup(s);
2464 return;
2466 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
2467 QEMU_THREAD_JOINABLE);
2468 s->migration_thread_running = true;
2471 void migration_global_dump(Monitor *mon)
2473 MigrationState *ms = migrate_get_current();
2475 monitor_printf(mon, "globals:\n");
2476 monitor_printf(mon, "store-global-state: %s\n",
2477 ms->store_global_state ? "on" : "off");
2478 monitor_printf(mon, "only-migratable: %s\n",
2479 ms->only_migratable ? "on" : "off");
2480 monitor_printf(mon, "send-configuration: %s\n",
2481 ms->send_configuration ? "on" : "off");
2482 monitor_printf(mon, "send-section-footer: %s\n",
2483 ms->send_section_footer ? "on" : "off");
2486 #define DEFINE_PROP_MIG_CAP(name, x) \
2487 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2489 static Property migration_properties[] = {
2490 DEFINE_PROP_BOOL("store-global-state", MigrationState,
2491 store_global_state, true),
2492 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
2493 DEFINE_PROP_BOOL("send-configuration", MigrationState,
2494 send_configuration, true),
2495 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
2496 send_section_footer, true),
2498 /* Migration parameters */
2499 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
2500 parameters.compress_level,
2501 DEFAULT_MIGRATE_COMPRESS_LEVEL),
2502 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
2503 parameters.compress_threads,
2504 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
2505 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
2506 parameters.decompress_threads,
2507 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
2508 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
2509 parameters.cpu_throttle_initial,
2510 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
2511 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
2512 parameters.cpu_throttle_increment,
2513 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
2514 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
2515 parameters.max_bandwidth, MAX_THROTTLE),
2516 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
2517 parameters.downtime_limit,
2518 DEFAULT_MIGRATE_SET_DOWNTIME),
2519 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
2520 parameters.x_checkpoint_delay,
2521 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
2522 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
2523 parameters.x_multifd_channels,
2524 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
2525 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
2526 parameters.x_multifd_page_count,
2527 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
2528 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
2529 parameters.xbzrle_cache_size,
2530 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
2532 /* Migration capabilities */
2533 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
2534 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
2535 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
2536 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
2537 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
2538 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
2539 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
2540 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
2541 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
2542 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
2543 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
2544 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
2546 DEFINE_PROP_END_OF_LIST(),
2549 static void migration_class_init(ObjectClass *klass, void *data)
2551 DeviceClass *dc = DEVICE_CLASS(klass);
2553 dc->user_creatable = false;
2554 dc->props = migration_properties;
2557 static void migration_instance_finalize(Object *obj)
2559 MigrationState *ms = MIGRATION_OBJ(obj);
2560 MigrationParameters *params = &ms->parameters;
2562 qemu_mutex_destroy(&ms->error_mutex);
2563 g_free(params->tls_hostname);
2564 g_free(params->tls_creds);
2565 qemu_sem_destroy(&ms->pause_sem);
2566 error_free(ms->error);
2569 static void migration_instance_init(Object *obj)
2571 MigrationState *ms = MIGRATION_OBJ(obj);
2572 MigrationParameters *params = &ms->parameters;
2574 ms->state = MIGRATION_STATUS_NONE;
2575 ms->mbps = -1;
2576 qemu_sem_init(&ms->pause_sem, 0);
2577 qemu_mutex_init(&ms->error_mutex);
2579 params->tls_hostname = g_strdup("");
2580 params->tls_creds = g_strdup("");
2582 /* Set has_* up only for parameter checks */
2583 params->has_compress_level = true;
2584 params->has_compress_threads = true;
2585 params->has_decompress_threads = true;
2586 params->has_cpu_throttle_initial = true;
2587 params->has_cpu_throttle_increment = true;
2588 params->has_max_bandwidth = true;
2589 params->has_downtime_limit = true;
2590 params->has_x_checkpoint_delay = true;
2591 params->has_block_incremental = true;
2592 params->has_x_multifd_channels = true;
2593 params->has_x_multifd_page_count = true;
2594 params->has_xbzrle_cache_size = true;
2598 * Return true if check pass, false otherwise. Error will be put
2599 * inside errp if provided.
2601 static bool migration_object_check(MigrationState *ms, Error **errp)
2603 MigrationCapabilityStatusList *head = NULL;
2604 /* Assuming all off */
2605 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
2606 int i;
2608 if (!migrate_params_check(&ms->parameters, errp)) {
2609 return false;
2612 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
2613 if (ms->enabled_capabilities[i]) {
2614 head = migrate_cap_add(head, i, true);
2618 ret = migrate_caps_check(cap_list, head, errp);
2620 /* It works with head == NULL */
2621 qapi_free_MigrationCapabilityStatusList(head);
2623 return ret;
2626 static const TypeInfo migration_type = {
2627 .name = TYPE_MIGRATION,
2629 * NOTE: TYPE_MIGRATION is not really a device, as the object is
2630 * not created using qdev_create(), it is not attached to the qdev
2631 * device tree, and it is never realized.
2633 * TODO: Make this TYPE_OBJECT once QOM provides something like
2634 * TYPE_DEVICE's "-global" properties.
2636 .parent = TYPE_DEVICE,
2637 .class_init = migration_class_init,
2638 .class_size = sizeof(MigrationClass),
2639 .instance_size = sizeof(MigrationState),
2640 .instance_init = migration_instance_init,
2641 .instance_finalize = migration_instance_finalize,
2644 static void register_migration_types(void)
2646 type_register_static(&migration_type);
2649 type_init(register_migration_types);