4 * Copyright IBM, Corp. 2008
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"
25 #include "migration/global_state.h"
26 #include "migration/misc.h"
27 #include "migration.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"
40 #include "postcopy-ram.h"
41 #include "qemu/thread.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
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
74 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
76 /* Migration XBZRLE default cache size */
77 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
79 /* The delay time (in ms) between two COLO checkpoints */
80 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
81 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
82 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
84 /* Background transfer rate for postcopy, 0 means unlimited, note
85 * that page requests can still exceed this limit.
87 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
89 static NotifierList migration_state_notifiers =
90 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
92 static bool deferred_incoming;
94 /* Messages sent on the return path from destination to source */
95 enum mig_rp_message_type {
96 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
97 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
98 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
100 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
101 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
102 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
103 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
108 /* When we add fault tolerance, we could have several
109 migrations at once. For now we don't need to add
110 dynamic creation of migration */
112 static MigrationState *current_migration;
113 static MigrationIncomingState *current_incoming;
115 static bool migration_object_check(MigrationState *ms, Error **errp);
116 static int migration_maybe_pause(MigrationState *s,
117 int *current_active_state,
120 void migration_object_init(void)
122 MachineState *ms = MACHINE(qdev_get_machine());
125 /* This can only be called once. */
126 assert(!current_migration);
127 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
130 * Init the migrate incoming object as well no matter whether
131 * we'll use it or not.
133 assert(!current_incoming);
134 current_incoming = g_new0(MigrationIncomingState, 1);
135 current_incoming->state = MIGRATION_STATUS_NONE;
136 current_incoming->postcopy_remote_fds =
137 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
138 qemu_mutex_init(¤t_incoming->rp_mutex);
139 qemu_event_init(¤t_incoming->main_thread_load_event, false);
140 qemu_sem_init(¤t_incoming->postcopy_pause_sem_dst, 0);
141 qemu_sem_init(¤t_incoming->postcopy_pause_sem_fault, 0);
143 init_dirty_bitmap_incoming_migration();
145 if (!migration_object_check(current_migration, &err)) {
146 error_report_err(err);
151 * We cannot really do this in migration_instance_init() since at
152 * that time global properties are not yet applied, then this
153 * value will be definitely replaced by something else.
155 if (ms->enforce_config_section) {
156 current_migration->send_configuration = true;
160 void migration_object_finalize(void)
162 object_unref(OBJECT(current_migration));
166 MigrationState *migrate_get_current(void)
168 /* This can only be called after the object created. */
169 assert(current_migration);
170 return current_migration;
173 MigrationIncomingState *migration_incoming_get_current(void)
175 assert(current_incoming);
176 return current_incoming;
179 void migration_incoming_state_destroy(void)
181 struct MigrationIncomingState *mis = migration_incoming_get_current();
183 if (mis->to_src_file) {
184 /* Tell source that we are done */
185 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
186 qemu_fclose(mis->to_src_file);
187 mis->to_src_file = NULL;
190 if (mis->from_src_file) {
191 qemu_fclose(mis->from_src_file);
192 mis->from_src_file = NULL;
194 if (mis->postcopy_remote_fds) {
195 g_array_free(mis->postcopy_remote_fds, TRUE);
196 mis->postcopy_remote_fds = NULL;
199 qemu_event_reset(&mis->main_thread_load_event);
202 static void migrate_generate_event(int new_state)
204 if (migrate_use_events()) {
205 qapi_event_send_migration(new_state);
209 static bool migrate_late_block_activate(void)
213 s = migrate_get_current();
215 return s->enabled_capabilities[
216 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
220 * Called on -incoming with a defer: uri.
221 * The migration can be started later after any parameters have been
224 static void deferred_incoming_migration(Error **errp)
226 if (deferred_incoming) {
227 error_setg(errp, "Incoming migration already deferred");
229 deferred_incoming = true;
233 * Send a message on the return channel back to the source
236 static int migrate_send_rp_message(MigrationIncomingState *mis,
237 enum mig_rp_message_type message_type,
238 uint16_t len, void *data)
242 trace_migrate_send_rp_message((int)message_type, len);
243 qemu_mutex_lock(&mis->rp_mutex);
246 * It's possible that the file handle got lost due to network
249 if (!mis->to_src_file) {
254 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
255 qemu_put_be16(mis->to_src_file, len);
256 qemu_put_buffer(mis->to_src_file, data, len);
257 qemu_fflush(mis->to_src_file);
259 /* It's possible that qemu file got error during sending */
260 ret = qemu_file_get_error(mis->to_src_file);
263 qemu_mutex_unlock(&mis->rp_mutex);
267 /* Request a range of pages from the source VM at the given
269 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
270 * as the last request (a name must have been given previously)
271 * Start: Address offset within the RB
272 * Len: Length in bytes required - must be a multiple of pagesize
274 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
275 ram_addr_t start, size_t len)
277 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
278 size_t msglen = 12; /* start + len */
279 enum mig_rp_message_type msg_type;
281 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
282 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
285 int rbname_len = strlen(rbname);
286 assert(rbname_len < 256);
288 bufc[msglen++] = rbname_len;
289 memcpy(bufc + msglen, rbname, rbname_len);
290 msglen += rbname_len;
291 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
293 msg_type = MIG_RP_MSG_REQ_PAGES;
296 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
299 void qemu_start_incoming_migration(const char *uri, Error **errp)
303 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
304 if (!strcmp(uri, "defer")) {
305 deferred_incoming_migration(errp);
306 } else if (strstart(uri, "tcp:", &p)) {
307 tcp_start_incoming_migration(p, errp);
309 } else if (strstart(uri, "rdma:", &p)) {
310 rdma_start_incoming_migration(p, errp);
312 } else if (strstart(uri, "exec:", &p)) {
313 exec_start_incoming_migration(p, errp);
314 } else if (strstart(uri, "unix:", &p)) {
315 unix_start_incoming_migration(p, errp);
316 } else if (strstart(uri, "fd:", &p)) {
317 fd_start_incoming_migration(p, errp);
319 error_setg(errp, "unknown migration protocol: %s", uri);
323 static void process_incoming_migration_bh(void *opaque)
325 Error *local_err = NULL;
326 MigrationIncomingState *mis = opaque;
328 /* If capability late_block_activate is set:
329 * Only fire up the block code now if we're going to restart the
330 * VM, else 'cont' will do it.
331 * This causes file locking to happen; so we don't want it to happen
332 * unless we really are starting the VM.
334 if (!migrate_late_block_activate() ||
335 (autostart && (!global_state_received() ||
336 global_state_get_runstate() == RUN_STATE_RUNNING))) {
337 /* Make sure all file formats flush their mutable metadata.
338 * If we get an error here, just don't restart the VM yet. */
339 bdrv_invalidate_cache_all(&local_err);
341 error_report_err(local_err);
348 * This must happen after all error conditions are dealt with and
349 * we're sure the VM is going to be running on this host.
351 qemu_announce_self();
353 if (multifd_load_cleanup(&local_err) != 0) {
354 error_report_err(local_err);
357 /* If global state section was not received or we are in running
358 state, we need to obey autostart. Any other state is set with
361 dirty_bitmap_mig_before_vm_start();
363 if (!global_state_received() ||
364 global_state_get_runstate() == RUN_STATE_RUNNING) {
368 runstate_set(RUN_STATE_PAUSED);
371 runstate_set(global_state_get_runstate());
374 * This must happen after any state changes since as soon as an external
375 * observer sees this event they might start to prod at the VM assuming
378 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
379 MIGRATION_STATUS_COMPLETED);
380 qemu_bh_delete(mis->bh);
381 migration_incoming_state_destroy();
384 static void process_incoming_migration_co(void *opaque)
386 MigrationIncomingState *mis = migration_incoming_get_current();
390 assert(mis->from_src_file);
391 mis->migration_incoming_co = qemu_coroutine_self();
392 mis->largest_page_size = qemu_ram_pagesize_largest();
393 postcopy_state_set(POSTCOPY_INCOMING_NONE);
394 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
395 MIGRATION_STATUS_ACTIVE);
396 ret = qemu_loadvm_state(mis->from_src_file);
398 ps = postcopy_state_get();
399 trace_process_incoming_migration_co_end(ret, ps);
400 if (ps != POSTCOPY_INCOMING_NONE) {
401 if (ps == POSTCOPY_INCOMING_ADVISE) {
403 * Where a migration had postcopy enabled (and thus went to advise)
404 * but managed to complete within the precopy period, we can use
407 postcopy_ram_incoming_cleanup(mis);
408 } else if (ret >= 0) {
410 * Postcopy was started, cleanup should happen at the end of the
413 trace_process_incoming_migration_co_postcopy_end_main();
416 /* Else if something went wrong then just fall out of the normal exit */
419 /* we get COLO info, and know if we are in COLO mode */
420 if (!ret && migration_incoming_enable_colo()) {
421 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
422 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
423 mis->have_colo_incoming_thread = true;
424 qemu_coroutine_yield();
426 /* Wait checkpoint incoming thread exit before free resource */
427 qemu_thread_join(&mis->colo_incoming_thread);
431 Error *local_err = NULL;
433 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
434 MIGRATION_STATUS_FAILED);
435 error_report("load of migration failed: %s", strerror(-ret));
436 qemu_fclose(mis->from_src_file);
437 if (multifd_load_cleanup(&local_err) != 0) {
438 error_report_err(local_err);
442 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
443 qemu_bh_schedule(mis->bh);
444 mis->migration_incoming_co = NULL;
447 static void migration_incoming_setup(QEMUFile *f)
449 MigrationIncomingState *mis = migration_incoming_get_current();
451 if (multifd_load_setup() != 0) {
452 /* We haven't been able to create multifd threads
453 nothing better to do */
457 if (!mis->from_src_file) {
458 mis->from_src_file = f;
460 qemu_file_set_blocking(f, false);
463 void migration_incoming_process(void)
465 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
466 qemu_coroutine_enter(co);
469 /* Returns true if recovered from a paused migration, otherwise false */
470 static bool postcopy_try_recover(QEMUFile *f)
472 MigrationIncomingState *mis = migration_incoming_get_current();
474 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
475 /* Resumed from a paused postcopy migration */
477 mis->from_src_file = f;
478 /* Postcopy has standalone thread to do vm load */
479 qemu_file_set_blocking(f, true);
481 /* Re-configure the return path */
482 mis->to_src_file = qemu_file_get_return_path(f);
484 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
485 MIGRATION_STATUS_POSTCOPY_RECOVER);
488 * Here, we only wake up the main loading thread (while the
489 * fault thread will still be waiting), so that we can receive
490 * commands from source now, and answer it if needed. The
491 * fault thread will be woken up afterwards until we are sure
492 * that source is ready to reply to page requests.
494 qemu_sem_post(&mis->postcopy_pause_sem_dst);
501 void migration_fd_process_incoming(QEMUFile *f)
503 if (postcopy_try_recover(f)) {
507 migration_incoming_setup(f);
508 migration_incoming_process();
511 void migration_ioc_process_incoming(QIOChannel *ioc)
513 MigrationIncomingState *mis = migration_incoming_get_current();
514 bool start_migration;
516 if (!mis->from_src_file) {
517 /* The first connection (multifd may have multiple) */
518 QEMUFile *f = qemu_fopen_channel_input(ioc);
520 /* If it's a recovery, we're done */
521 if (postcopy_try_recover(f)) {
525 migration_incoming_setup(f);
528 * Common migration only needs one channel, so we can start
529 * right now. Multifd needs more than one channel, we wait.
531 start_migration = !migrate_use_multifd();
533 /* Multiple connections */
534 assert(migrate_use_multifd());
535 start_migration = multifd_recv_new_channel(ioc);
538 if (start_migration) {
539 migration_incoming_process();
544 * @migration_has_all_channels: We have received all channels that we need
546 * Returns true when we have got connections to all the channels that
547 * we need for migration.
549 bool migration_has_all_channels(void)
551 MigrationIncomingState *mis = migration_incoming_get_current();
554 all_channels = multifd_recv_all_channels_created();
556 return all_channels && mis->from_src_file != NULL;
560 * Send a 'SHUT' message on the return channel with the given value
561 * to indicate that we've finished with the RP. Non-0 value indicates
564 void migrate_send_rp_shut(MigrationIncomingState *mis,
569 buf = cpu_to_be32(value);
570 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
574 * Send a 'PONG' message on the return channel with the given value
575 * (normally in response to a 'PING')
577 void migrate_send_rp_pong(MigrationIncomingState *mis,
582 buf = cpu_to_be32(value);
583 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
586 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
594 * First, we send the header part. It contains only the len of
595 * idstr, and the idstr itself.
597 len = strlen(block_name);
599 memcpy(buf + 1, block_name, len);
601 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
602 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
607 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
610 * Next, we dump the received bitmap to the stream.
612 * TODO: currently we are safe since we are the only one that is
613 * using the to_src_file handle (fault thread is still paused),
614 * and it's ok even not taking the mutex. However the best way is
615 * to take the lock before sending the message header, and release
616 * the lock after sending the bitmap.
618 qemu_mutex_lock(&mis->rp_mutex);
619 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
620 qemu_mutex_unlock(&mis->rp_mutex);
622 trace_migrate_send_rp_recv_bitmap(block_name, res);
625 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
629 buf = cpu_to_be32(value);
630 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
633 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
635 MigrationCapabilityStatusList *head = NULL;
636 MigrationCapabilityStatusList *caps;
637 MigrationState *s = migrate_get_current();
640 caps = NULL; /* silence compiler warning */
641 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
642 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
643 if (i == MIGRATION_CAPABILITY_BLOCK) {
648 head = g_malloc0(sizeof(*caps));
651 caps->next = g_malloc0(sizeof(*caps));
655 g_malloc(sizeof(*caps->value));
656 caps->value->capability = i;
657 caps->value->state = s->enabled_capabilities[i];
663 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
665 MigrationParameters *params;
666 MigrationState *s = migrate_get_current();
668 /* TODO use QAPI_CLONE() instead of duplicating it inline */
669 params = g_malloc0(sizeof(*params));
670 params->has_compress_level = true;
671 params->compress_level = s->parameters.compress_level;
672 params->has_compress_threads = true;
673 params->compress_threads = s->parameters.compress_threads;
674 params->has_compress_wait_thread = true;
675 params->compress_wait_thread = s->parameters.compress_wait_thread;
676 params->has_decompress_threads = true;
677 params->decompress_threads = s->parameters.decompress_threads;
678 params->has_cpu_throttle_initial = true;
679 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
680 params->has_cpu_throttle_increment = true;
681 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
682 params->has_tls_creds = true;
683 params->tls_creds = g_strdup(s->parameters.tls_creds);
684 params->has_tls_hostname = true;
685 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
686 params->has_max_bandwidth = true;
687 params->max_bandwidth = s->parameters.max_bandwidth;
688 params->has_downtime_limit = true;
689 params->downtime_limit = s->parameters.downtime_limit;
690 params->has_x_checkpoint_delay = true;
691 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
692 params->has_block_incremental = true;
693 params->block_incremental = s->parameters.block_incremental;
694 params->has_x_multifd_channels = true;
695 params->x_multifd_channels = s->parameters.x_multifd_channels;
696 params->has_x_multifd_page_count = true;
697 params->x_multifd_page_count = s->parameters.x_multifd_page_count;
698 params->has_xbzrle_cache_size = true;
699 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
700 params->has_max_postcopy_bandwidth = true;
701 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
702 params->has_max_cpu_throttle = true;
703 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
709 * Return true if we're already in the middle of a migration
710 * (i.e. any of the active or setup states)
712 static bool migration_is_setup_or_active(int state)
715 case MIGRATION_STATUS_ACTIVE:
716 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
717 case MIGRATION_STATUS_POSTCOPY_PAUSED:
718 case MIGRATION_STATUS_POSTCOPY_RECOVER:
719 case MIGRATION_STATUS_SETUP:
720 case MIGRATION_STATUS_PRE_SWITCHOVER:
721 case MIGRATION_STATUS_DEVICE:
730 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
732 info->has_ram = true;
733 info->ram = g_malloc0(sizeof(*info->ram));
734 info->ram->transferred = ram_counters.transferred;
735 info->ram->total = ram_bytes_total();
736 info->ram->duplicate = ram_counters.duplicate;
737 /* legacy value. It is not used anymore */
738 info->ram->skipped = 0;
739 info->ram->normal = ram_counters.normal;
740 info->ram->normal_bytes = ram_counters.normal *
741 qemu_target_page_size();
742 info->ram->mbps = s->mbps;
743 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
744 info->ram->postcopy_requests = ram_counters.postcopy_requests;
745 info->ram->page_size = qemu_target_page_size();
746 info->ram->multifd_bytes = ram_counters.multifd_bytes;
748 if (migrate_use_xbzrle()) {
749 info->has_xbzrle_cache = true;
750 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
751 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
752 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
753 info->xbzrle_cache->pages = xbzrle_counters.pages;
754 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
755 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
756 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
759 if (migrate_use_compression()) {
760 info->has_compression = true;
761 info->compression = g_malloc0(sizeof(*info->compression));
762 info->compression->pages = compression_counters.pages;
763 info->compression->busy = compression_counters.busy;
764 info->compression->busy_rate = compression_counters.busy_rate;
765 info->compression->compressed_size =
766 compression_counters.compressed_size;
767 info->compression->compression_rate =
768 compression_counters.compression_rate;
771 if (cpu_throttle_active()) {
772 info->has_cpu_throttle_percentage = true;
773 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
776 if (s->state != MIGRATION_STATUS_COMPLETED) {
777 info->ram->remaining = ram_bytes_remaining();
778 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
782 static void populate_disk_info(MigrationInfo *info)
784 if (blk_mig_active()) {
785 info->has_disk = true;
786 info->disk = g_malloc0(sizeof(*info->disk));
787 info->disk->transferred = blk_mig_bytes_transferred();
788 info->disk->remaining = blk_mig_bytes_remaining();
789 info->disk->total = blk_mig_bytes_total();
793 static void fill_source_migration_info(MigrationInfo *info)
795 MigrationState *s = migrate_get_current();
798 case MIGRATION_STATUS_NONE:
799 /* no migration has happened ever */
800 /* do not overwrite destination migration status */
803 case MIGRATION_STATUS_SETUP:
804 info->has_status = true;
805 info->has_total_time = false;
807 case MIGRATION_STATUS_ACTIVE:
808 case MIGRATION_STATUS_CANCELLING:
809 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
810 case MIGRATION_STATUS_PRE_SWITCHOVER:
811 case MIGRATION_STATUS_DEVICE:
812 case MIGRATION_STATUS_POSTCOPY_PAUSED:
813 case MIGRATION_STATUS_POSTCOPY_RECOVER:
814 /* TODO add some postcopy stats */
815 info->has_status = true;
816 info->has_total_time = true;
817 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
819 info->has_expected_downtime = true;
820 info->expected_downtime = s->expected_downtime;
821 info->has_setup_time = true;
822 info->setup_time = s->setup_time;
824 populate_ram_info(info, s);
825 populate_disk_info(info);
827 case MIGRATION_STATUS_COLO:
828 info->has_status = true;
829 /* TODO: display COLO specific information (checkpoint info etc.) */
831 case MIGRATION_STATUS_COMPLETED:
832 info->has_status = true;
833 info->has_total_time = true;
834 info->total_time = s->total_time;
835 info->has_downtime = true;
836 info->downtime = s->downtime;
837 info->has_setup_time = true;
838 info->setup_time = s->setup_time;
840 populate_ram_info(info, s);
842 case MIGRATION_STATUS_FAILED:
843 info->has_status = true;
845 info->has_error_desc = true;
846 info->error_desc = g_strdup(error_get_pretty(s->error));
849 case MIGRATION_STATUS_CANCELLED:
850 info->has_status = true;
853 info->status = s->state;
857 * @migration_caps_check - check capability validity
859 * @cap_list: old capability list, array of bool
860 * @params: new capabilities to be applied soon
861 * @errp: set *errp if the check failed, with reason
863 * Returns true if check passed, otherwise false.
865 static bool migrate_caps_check(bool *cap_list,
866 MigrationCapabilityStatusList *params,
869 MigrationCapabilityStatusList *cap;
870 bool old_postcopy_cap;
871 MigrationIncomingState *mis = migration_incoming_get_current();
873 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
875 for (cap = params; cap; cap = cap->next) {
876 cap_list[cap->value->capability] = cap->value->state;
879 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
880 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
881 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
883 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
888 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
889 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
890 /* The decompression threads asynchronously write into RAM
891 * rather than use the atomic copies needed to avoid
892 * userfaulting. It should be possible to fix the decompression
893 * threads for compatibility in future.
895 error_setg(errp, "Postcopy is not currently compatible "
900 /* This check is reasonably expensive, so only when it's being
901 * set the first time, also it's only the destination that needs
904 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
905 !postcopy_ram_supported_by_host(mis)) {
906 /* postcopy_ram_supported_by_host will have emitted a more
909 error_setg(errp, "Postcopy is not supported");
917 static void fill_destination_migration_info(MigrationInfo *info)
919 MigrationIncomingState *mis = migration_incoming_get_current();
921 switch (mis->state) {
922 case MIGRATION_STATUS_NONE:
925 case MIGRATION_STATUS_SETUP:
926 case MIGRATION_STATUS_CANCELLING:
927 case MIGRATION_STATUS_CANCELLED:
928 case MIGRATION_STATUS_ACTIVE:
929 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
930 case MIGRATION_STATUS_POSTCOPY_PAUSED:
931 case MIGRATION_STATUS_POSTCOPY_RECOVER:
932 case MIGRATION_STATUS_FAILED:
933 case MIGRATION_STATUS_COLO:
934 info->has_status = true;
936 case MIGRATION_STATUS_COMPLETED:
937 info->has_status = true;
938 fill_destination_postcopy_migration_info(info);
941 info->status = mis->state;
944 MigrationInfo *qmp_query_migrate(Error **errp)
946 MigrationInfo *info = g_malloc0(sizeof(*info));
948 fill_destination_migration_info(info);
949 fill_source_migration_info(info);
954 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
957 MigrationState *s = migrate_get_current();
958 MigrationCapabilityStatusList *cap;
959 bool cap_list[MIGRATION_CAPABILITY__MAX];
961 if (migration_is_setup_or_active(s->state)) {
962 error_setg(errp, QERR_MIGRATION_ACTIVE);
966 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
967 if (!migrate_caps_check(cap_list, params, errp)) {
971 for (cap = params; cap; cap = cap->next) {
972 s->enabled_capabilities[cap->value->capability] = cap->value->state;
977 * Check whether the parameters are valid. Error will be put into errp
978 * (if provided). Return true if valid, otherwise false.
980 static bool migrate_params_check(MigrationParameters *params, Error **errp)
982 if (params->has_compress_level &&
983 (params->compress_level > 9)) {
984 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
985 "is invalid, it should be in the range of 0 to 9");
989 if (params->has_compress_threads && (params->compress_threads < 1)) {
990 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
992 "is invalid, it should be in the range of 1 to 255");
996 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
997 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
998 "decompress_threads",
999 "is invalid, it should be in the range of 1 to 255");
1003 if (params->has_cpu_throttle_initial &&
1004 (params->cpu_throttle_initial < 1 ||
1005 params->cpu_throttle_initial > 99)) {
1006 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1007 "cpu_throttle_initial",
1008 "an integer in the range of 1 to 99");
1012 if (params->has_cpu_throttle_increment &&
1013 (params->cpu_throttle_increment < 1 ||
1014 params->cpu_throttle_increment > 99)) {
1015 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1016 "cpu_throttle_increment",
1017 "an integer in the range of 1 to 99");
1021 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1022 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
1023 " range of 0 to %zu bytes/second", SIZE_MAX);
1027 if (params->has_downtime_limit &&
1028 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1029 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1030 "the range of 0 to %d milliseconds",
1031 MAX_MIGRATE_DOWNTIME);
1035 /* x_checkpoint_delay is now always positive */
1037 if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
1038 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1040 "is invalid, it should be in the range of 1 to 255");
1043 if (params->has_x_multifd_page_count &&
1044 (params->x_multifd_page_count < 1 ||
1045 params->x_multifd_page_count > 10000)) {
1046 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1047 "multifd_page_count",
1048 "is invalid, it should be in the range of 1 to 10000");
1052 if (params->has_xbzrle_cache_size &&
1053 (params->xbzrle_cache_size < qemu_target_page_size() ||
1054 !is_power_of_2(params->xbzrle_cache_size))) {
1055 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1056 "xbzrle_cache_size",
1057 "is invalid, it should be bigger than target page size"
1058 " and a power of two");
1062 if (params->has_max_cpu_throttle &&
1063 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1064 params->max_cpu_throttle > 99)) {
1065 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1067 "an integer in the range of cpu_throttle_initial to 99");
1074 static void migrate_params_test_apply(MigrateSetParameters *params,
1075 MigrationParameters *dest)
1077 *dest = migrate_get_current()->parameters;
1079 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1081 if (params->has_compress_level) {
1082 dest->compress_level = params->compress_level;
1085 if (params->has_compress_threads) {
1086 dest->compress_threads = params->compress_threads;
1089 if (params->has_compress_wait_thread) {
1090 dest->compress_wait_thread = params->compress_wait_thread;
1093 if (params->has_decompress_threads) {
1094 dest->decompress_threads = params->decompress_threads;
1097 if (params->has_cpu_throttle_initial) {
1098 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1101 if (params->has_cpu_throttle_increment) {
1102 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1105 if (params->has_tls_creds) {
1106 assert(params->tls_creds->type == QTYPE_QSTRING);
1107 dest->tls_creds = g_strdup(params->tls_creds->u.s);
1110 if (params->has_tls_hostname) {
1111 assert(params->tls_hostname->type == QTYPE_QSTRING);
1112 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1115 if (params->has_max_bandwidth) {
1116 dest->max_bandwidth = params->max_bandwidth;
1119 if (params->has_downtime_limit) {
1120 dest->downtime_limit = params->downtime_limit;
1123 if (params->has_x_checkpoint_delay) {
1124 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1127 if (params->has_block_incremental) {
1128 dest->block_incremental = params->block_incremental;
1130 if (params->has_x_multifd_channels) {
1131 dest->x_multifd_channels = params->x_multifd_channels;
1133 if (params->has_x_multifd_page_count) {
1134 dest->x_multifd_page_count = params->x_multifd_page_count;
1136 if (params->has_xbzrle_cache_size) {
1137 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1139 if (params->has_max_postcopy_bandwidth) {
1140 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1142 if (params->has_max_cpu_throttle) {
1143 dest->max_cpu_throttle = params->max_cpu_throttle;
1147 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1149 MigrationState *s = migrate_get_current();
1151 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1153 if (params->has_compress_level) {
1154 s->parameters.compress_level = params->compress_level;
1157 if (params->has_compress_threads) {
1158 s->parameters.compress_threads = params->compress_threads;
1161 if (params->has_compress_wait_thread) {
1162 s->parameters.compress_wait_thread = params->compress_wait_thread;
1165 if (params->has_decompress_threads) {
1166 s->parameters.decompress_threads = params->decompress_threads;
1169 if (params->has_cpu_throttle_initial) {
1170 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1173 if (params->has_cpu_throttle_increment) {
1174 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1177 if (params->has_tls_creds) {
1178 g_free(s->parameters.tls_creds);
1179 assert(params->tls_creds->type == QTYPE_QSTRING);
1180 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1183 if (params->has_tls_hostname) {
1184 g_free(s->parameters.tls_hostname);
1185 assert(params->tls_hostname->type == QTYPE_QSTRING);
1186 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1189 if (params->has_max_bandwidth) {
1190 s->parameters.max_bandwidth = params->max_bandwidth;
1191 if (s->to_dst_file) {
1192 qemu_file_set_rate_limit(s->to_dst_file,
1193 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1197 if (params->has_downtime_limit) {
1198 s->parameters.downtime_limit = params->downtime_limit;
1201 if (params->has_x_checkpoint_delay) {
1202 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1203 if (migration_in_colo_state()) {
1204 colo_checkpoint_notify(s);
1208 if (params->has_block_incremental) {
1209 s->parameters.block_incremental = params->block_incremental;
1211 if (params->has_x_multifd_channels) {
1212 s->parameters.x_multifd_channels = params->x_multifd_channels;
1214 if (params->has_x_multifd_page_count) {
1215 s->parameters.x_multifd_page_count = params->x_multifd_page_count;
1217 if (params->has_xbzrle_cache_size) {
1218 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1219 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1221 if (params->has_max_postcopy_bandwidth) {
1222 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1224 if (params->has_max_cpu_throttle) {
1225 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1229 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1231 MigrationParameters tmp;
1233 /* TODO Rewrite "" to null instead */
1234 if (params->has_tls_creds
1235 && params->tls_creds->type == QTYPE_QNULL) {
1236 qobject_unref(params->tls_creds->u.n);
1237 params->tls_creds->type = QTYPE_QSTRING;
1238 params->tls_creds->u.s = strdup("");
1240 /* TODO Rewrite "" to null instead */
1241 if (params->has_tls_hostname
1242 && params->tls_hostname->type == QTYPE_QNULL) {
1243 qobject_unref(params->tls_hostname->u.n);
1244 params->tls_hostname->type = QTYPE_QSTRING;
1245 params->tls_hostname->u.s = strdup("");
1248 migrate_params_test_apply(params, &tmp);
1250 if (!migrate_params_check(&tmp, errp)) {
1251 /* Invalid parameter */
1255 migrate_params_apply(params, errp);
1259 void qmp_migrate_start_postcopy(Error **errp)
1261 MigrationState *s = migrate_get_current();
1263 if (!migrate_postcopy()) {
1264 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1265 " the start of migration");
1269 if (s->state == MIGRATION_STATUS_NONE) {
1270 error_setg(errp, "Postcopy must be started after migration has been"
1275 * we don't error if migration has finished since that would be racy
1276 * with issuing this command.
1278 atomic_set(&s->start_postcopy, true);
1281 /* shared migration helpers */
1283 void migrate_set_state(int *state, int old_state, int new_state)
1285 assert(new_state < MIGRATION_STATUS__MAX);
1286 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1287 trace_migrate_set_state(MigrationStatus_str(new_state));
1288 migrate_generate_event(new_state);
1292 static MigrationCapabilityStatusList *migrate_cap_add(
1293 MigrationCapabilityStatusList *list,
1294 MigrationCapability index,
1297 MigrationCapabilityStatusList *cap;
1299 cap = g_new0(MigrationCapabilityStatusList, 1);
1300 cap->value = g_new0(MigrationCapabilityStatus, 1);
1301 cap->value->capability = index;
1302 cap->value->state = state;
1308 void migrate_set_block_enabled(bool value, Error **errp)
1310 MigrationCapabilityStatusList *cap;
1312 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1313 qmp_migrate_set_capabilities(cap, errp);
1314 qapi_free_MigrationCapabilityStatusList(cap);
1317 static void migrate_set_block_incremental(MigrationState *s, bool value)
1319 s->parameters.block_incremental = value;
1322 static void block_cleanup_parameters(MigrationState *s)
1324 if (s->must_remove_block_options) {
1325 /* setting to false can never fail */
1326 migrate_set_block_enabled(false, &error_abort);
1327 migrate_set_block_incremental(s, false);
1328 s->must_remove_block_options = false;
1332 static void migrate_fd_cleanup(void *opaque)
1334 MigrationState *s = opaque;
1336 qemu_bh_delete(s->cleanup_bh);
1337 s->cleanup_bh = NULL;
1339 qemu_savevm_state_cleanup();
1341 if (s->to_dst_file) {
1342 Error *local_err = NULL;
1345 trace_migrate_fd_cleanup();
1346 qemu_mutex_unlock_iothread();
1347 if (s->migration_thread_running) {
1348 qemu_thread_join(&s->thread);
1349 s->migration_thread_running = false;
1351 qemu_mutex_lock_iothread();
1353 if (multifd_save_cleanup(&local_err) != 0) {
1354 error_report_err(local_err);
1356 qemu_mutex_lock(&s->qemu_file_lock);
1357 tmp = s->to_dst_file;
1358 s->to_dst_file = NULL;
1359 qemu_mutex_unlock(&s->qemu_file_lock);
1361 * Close the file handle without the lock to make sure the
1362 * critical section won't block for long.
1367 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1368 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
1370 if (s->state == MIGRATION_STATUS_CANCELLING) {
1371 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1372 MIGRATION_STATUS_CANCELLED);
1376 /* It is used on info migrate. We can't free it */
1377 error_report_err(error_copy(s->error));
1379 notifier_list_notify(&migration_state_notifiers, s);
1380 block_cleanup_parameters(s);
1383 void migrate_set_error(MigrationState *s, const Error *error)
1385 qemu_mutex_lock(&s->error_mutex);
1387 s->error = error_copy(error);
1389 qemu_mutex_unlock(&s->error_mutex);
1392 void migrate_fd_error(MigrationState *s, const Error *error)
1394 trace_migrate_fd_error(error_get_pretty(error));
1395 assert(s->to_dst_file == NULL);
1396 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1397 MIGRATION_STATUS_FAILED);
1398 migrate_set_error(s, error);
1401 static void migrate_fd_cancel(MigrationState *s)
1404 QEMUFile *f = migrate_get_current()->to_dst_file;
1405 trace_migrate_fd_cancel();
1407 if (s->rp_state.from_dst_file) {
1408 /* shutdown the rp socket, so causing the rp thread to shutdown */
1409 qemu_file_shutdown(s->rp_state.from_dst_file);
1413 old_state = s->state;
1414 if (!migration_is_setup_or_active(old_state)) {
1417 /* If the migration is paused, kick it out of the pause */
1418 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1419 qemu_sem_post(&s->pause_sem);
1421 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1422 } while (s->state != MIGRATION_STATUS_CANCELLING);
1425 * If we're unlucky the migration code might be stuck somewhere in a
1426 * send/write while the network has failed and is waiting to timeout;
1427 * if we've got shutdown(2) available then we can force it to quit.
1428 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1429 * called in a bh, so there is no race against this cancel.
1431 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1432 qemu_file_shutdown(f);
1434 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1435 Error *local_err = NULL;
1437 bdrv_invalidate_cache_all(&local_err);
1439 error_report_err(local_err);
1441 s->block_inactive = false;
1446 void add_migration_state_change_notifier(Notifier *notify)
1448 notifier_list_add(&migration_state_notifiers, notify);
1451 void remove_migration_state_change_notifier(Notifier *notify)
1453 notifier_remove(notify);
1456 bool migration_in_setup(MigrationState *s)
1458 return s->state == MIGRATION_STATUS_SETUP;
1461 bool migration_has_finished(MigrationState *s)
1463 return s->state == MIGRATION_STATUS_COMPLETED;
1466 bool migration_has_failed(MigrationState *s)
1468 return (s->state == MIGRATION_STATUS_CANCELLED ||
1469 s->state == MIGRATION_STATUS_FAILED);
1472 bool migration_in_postcopy(void)
1474 MigrationState *s = migrate_get_current();
1476 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1479 bool migration_in_postcopy_after_devices(MigrationState *s)
1481 return migration_in_postcopy() && s->postcopy_after_devices;
1484 bool migration_is_idle(void)
1486 MigrationState *s = migrate_get_current();
1489 case MIGRATION_STATUS_NONE:
1490 case MIGRATION_STATUS_CANCELLED:
1491 case MIGRATION_STATUS_COMPLETED:
1492 case MIGRATION_STATUS_FAILED:
1494 case MIGRATION_STATUS_SETUP:
1495 case MIGRATION_STATUS_CANCELLING:
1496 case MIGRATION_STATUS_ACTIVE:
1497 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1498 case MIGRATION_STATUS_COLO:
1499 case MIGRATION_STATUS_PRE_SWITCHOVER:
1500 case MIGRATION_STATUS_DEVICE:
1502 case MIGRATION_STATUS__MAX:
1503 g_assert_not_reached();
1509 void migrate_init(MigrationState *s)
1512 * Reinitialise all migration state, except
1513 * parameters/capabilities that the user set, and
1519 s->to_dst_file = NULL;
1520 s->state = MIGRATION_STATUS_NONE;
1521 s->rp_state.from_dst_file = NULL;
1522 s->rp_state.error = false;
1525 s->expected_downtime = 0;
1527 s->start_postcopy = false;
1528 s->postcopy_after_devices = false;
1529 s->migration_thread_running = false;
1530 error_free(s->error);
1533 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1535 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1537 s->vm_was_running = false;
1538 s->iteration_initial_bytes = 0;
1539 s->threshold_size = 0;
1542 static GSList *migration_blockers;
1544 int migrate_add_blocker(Error *reason, Error **errp)
1546 if (migrate_get_current()->only_migratable) {
1547 error_propagate(errp, error_copy(reason));
1548 error_prepend(errp, "disallowing migration blocker "
1549 "(--only_migratable) for: ");
1553 if (migration_is_idle()) {
1554 migration_blockers = g_slist_prepend(migration_blockers, reason);
1558 error_propagate(errp, error_copy(reason));
1559 error_prepend(errp, "disallowing migration blocker (migration in "
1564 void migrate_del_blocker(Error *reason)
1566 migration_blockers = g_slist_remove(migration_blockers, reason);
1569 void qmp_migrate_incoming(const char *uri, Error **errp)
1571 Error *local_err = NULL;
1572 static bool once = true;
1574 if (!deferred_incoming) {
1575 error_setg(errp, "For use with '-incoming defer'");
1579 error_setg(errp, "The incoming migration has already been started");
1582 qemu_start_incoming_migration(uri, &local_err);
1585 error_propagate(errp, local_err);
1592 void qmp_migrate_recover(const char *uri, Error **errp)
1594 MigrationIncomingState *mis = migration_incoming_get_current();
1596 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1597 error_setg(errp, "Migrate recover can only be run "
1598 "when postcopy is paused.");
1602 if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1603 false, true) == true) {
1604 error_setg(errp, "Migrate recovery is triggered already");
1609 * Note that this call will never start a real migration; it will
1610 * only re-setup the migration stream and poke existing migration
1611 * to continue using that newly established channel.
1613 qemu_start_incoming_migration(uri, errp);
1616 void qmp_migrate_pause(Error **errp)
1618 MigrationState *ms = migrate_get_current();
1619 MigrationIncomingState *mis = migration_incoming_get_current();
1622 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1623 /* Source side, during postcopy */
1624 qemu_mutex_lock(&ms->qemu_file_lock);
1625 ret = qemu_file_shutdown(ms->to_dst_file);
1626 qemu_mutex_unlock(&ms->qemu_file_lock);
1628 error_setg(errp, "Failed to pause source migration");
1633 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1634 ret = qemu_file_shutdown(mis->from_src_file);
1636 error_setg(errp, "Failed to pause destination migration");
1641 error_setg(errp, "migrate-pause is currently only supported "
1642 "during postcopy-active state");
1645 bool migration_is_blocked(Error **errp)
1647 if (qemu_savevm_state_blocked(errp)) {
1651 if (migration_blockers) {
1652 error_propagate(errp, error_copy(migration_blockers->data));
1659 /* Returns true if continue to migrate, or false if error detected */
1660 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1661 bool resume, Error **errp)
1663 Error *local_err = NULL;
1666 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1667 error_setg(errp, "Cannot resume if there is no "
1668 "paused migration");
1673 * Postcopy recovery won't work well with release-ram
1674 * capability since release-ram will drop the page buffer as
1675 * long as the page is put into the send buffer. So if there
1676 * is a network failure happened, any page buffers that have
1677 * not yet reached the destination VM but have already been
1678 * sent from the source VM will be lost forever. Let's refuse
1679 * the client from resuming such a postcopy migration.
1680 * Luckily release-ram was designed to only be used when src
1681 * and destination VMs are on the same host, so it should be
1684 if (migrate_release_ram()) {
1685 error_setg(errp, "Postcopy recovery cannot work "
1686 "when release-ram capability is set");
1690 /* This is a resume, skip init status */
1694 if (migration_is_setup_or_active(s->state) ||
1695 s->state == MIGRATION_STATUS_CANCELLING ||
1696 s->state == MIGRATION_STATUS_COLO) {
1697 error_setg(errp, QERR_MIGRATION_ACTIVE);
1701 if (runstate_check(RUN_STATE_INMIGRATE)) {
1702 error_setg(errp, "Guest is waiting for an incoming migration");
1706 if (migration_is_blocked(errp)) {
1710 if (blk || blk_inc) {
1711 if (migrate_use_block() || migrate_use_block_incremental()) {
1712 error_setg(errp, "Command options are incompatible with "
1713 "current migration capabilities");
1716 migrate_set_block_enabled(true, &local_err);
1718 error_propagate(errp, local_err);
1721 s->must_remove_block_options = true;
1725 migrate_set_block_incremental(s, true);
1733 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1734 bool has_inc, bool inc, bool has_detach, bool detach,
1735 bool has_resume, bool resume, Error **errp)
1737 Error *local_err = NULL;
1738 MigrationState *s = migrate_get_current();
1741 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1742 has_resume && resume, errp)) {
1743 /* Error detected, put into errp */
1747 if (strstart(uri, "tcp:", &p)) {
1748 tcp_start_outgoing_migration(s, p, &local_err);
1750 } else if (strstart(uri, "rdma:", &p)) {
1751 rdma_start_outgoing_migration(s, p, &local_err);
1753 } else if (strstart(uri, "exec:", &p)) {
1754 exec_start_outgoing_migration(s, p, &local_err);
1755 } else if (strstart(uri, "unix:", &p)) {
1756 unix_start_outgoing_migration(s, p, &local_err);
1757 } else if (strstart(uri, "fd:", &p)) {
1758 fd_start_outgoing_migration(s, p, &local_err);
1760 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1761 "a valid migration protocol");
1762 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1763 MIGRATION_STATUS_FAILED);
1764 block_cleanup_parameters(s);
1769 migrate_fd_error(s, local_err);
1770 error_propagate(errp, local_err);
1775 void qmp_migrate_cancel(Error **errp)
1777 migrate_fd_cancel(migrate_get_current());
1780 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1782 MigrationState *s = migrate_get_current();
1783 if (s->state != state) {
1784 error_setg(errp, "Migration not in expected state: %s",
1785 MigrationStatus_str(s->state));
1788 qemu_sem_post(&s->pause_sem);
1791 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1793 MigrateSetParameters p = {
1794 .has_xbzrle_cache_size = true,
1795 .xbzrle_cache_size = value,
1798 qmp_migrate_set_parameters(&p, errp);
1801 int64_t qmp_query_migrate_cache_size(Error **errp)
1803 return migrate_xbzrle_cache_size();
1806 void qmp_migrate_set_speed(int64_t value, Error **errp)
1808 MigrateSetParameters p = {
1809 .has_max_bandwidth = true,
1810 .max_bandwidth = value,
1813 qmp_migrate_set_parameters(&p, errp);
1816 void qmp_migrate_set_downtime(double value, Error **errp)
1818 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1819 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1820 "the range of 0 to %d seconds",
1821 MAX_MIGRATE_DOWNTIME_SECONDS);
1825 value *= 1000; /* Convert to milliseconds */
1826 value = MAX(0, MIN(INT64_MAX, value));
1828 MigrateSetParameters p = {
1829 .has_downtime_limit = true,
1830 .downtime_limit = value,
1833 qmp_migrate_set_parameters(&p, errp);
1836 bool migrate_release_ram(void)
1840 s = migrate_get_current();
1842 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1845 bool migrate_postcopy_ram(void)
1849 s = migrate_get_current();
1851 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1854 bool migrate_postcopy(void)
1856 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1859 bool migrate_auto_converge(void)
1863 s = migrate_get_current();
1865 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1868 bool migrate_zero_blocks(void)
1872 s = migrate_get_current();
1874 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1877 bool migrate_postcopy_blocktime(void)
1881 s = migrate_get_current();
1883 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
1886 bool migrate_use_compression(void)
1890 s = migrate_get_current();
1892 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1895 int migrate_compress_level(void)
1899 s = migrate_get_current();
1901 return s->parameters.compress_level;
1904 int migrate_compress_threads(void)
1908 s = migrate_get_current();
1910 return s->parameters.compress_threads;
1913 int migrate_compress_wait_thread(void)
1917 s = migrate_get_current();
1919 return s->parameters.compress_wait_thread;
1922 int migrate_decompress_threads(void)
1926 s = migrate_get_current();
1928 return s->parameters.decompress_threads;
1931 bool migrate_dirty_bitmaps(void)
1935 s = migrate_get_current();
1937 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1940 bool migrate_use_events(void)
1944 s = migrate_get_current();
1946 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1949 bool migrate_use_multifd(void)
1953 s = migrate_get_current();
1955 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1958 bool migrate_pause_before_switchover(void)
1962 s = migrate_get_current();
1964 return s->enabled_capabilities[
1965 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1968 int migrate_multifd_channels(void)
1972 s = migrate_get_current();
1974 return s->parameters.x_multifd_channels;
1977 int migrate_multifd_page_count(void)
1981 s = migrate_get_current();
1983 return s->parameters.x_multifd_page_count;
1986 int migrate_use_xbzrle(void)
1990 s = migrate_get_current();
1992 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1995 int64_t migrate_xbzrle_cache_size(void)
1999 s = migrate_get_current();
2001 return s->parameters.xbzrle_cache_size;
2004 static int64_t migrate_max_postcopy_bandwidth(void)
2008 s = migrate_get_current();
2010 return s->parameters.max_postcopy_bandwidth;
2013 bool migrate_use_block(void)
2017 s = migrate_get_current();
2019 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2022 bool migrate_use_return_path(void)
2026 s = migrate_get_current();
2028 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2031 bool migrate_use_block_incremental(void)
2035 s = migrate_get_current();
2037 return s->parameters.block_incremental;
2040 /* migration thread support */
2042 * Something bad happened to the RP stream, mark an error
2043 * The caller shall print or trace something to indicate why
2045 static void mark_source_rp_bad(MigrationState *s)
2047 s->rp_state.error = true;
2050 static struct rp_cmd_args {
2051 ssize_t len; /* -1 = variable */
2054 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2055 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2056 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2057 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2058 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2059 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2060 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2061 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2065 * Process a request for pages received on the return path,
2066 * We're allowed to send more than requested (e.g. to round to our page size)
2067 * and we don't need to send pages that have already been sent.
2069 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2070 ram_addr_t start, size_t len)
2072 long our_host_ps = getpagesize();
2074 trace_migrate_handle_rp_req_pages(rbname, start, len);
2077 * Since we currently insist on matching page sizes, just sanity check
2078 * we're being asked for whole host pages.
2080 if (start & (our_host_ps-1) ||
2081 (len & (our_host_ps-1))) {
2082 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2083 " len: %zd", __func__, start, len);
2084 mark_source_rp_bad(ms);
2088 if (ram_save_queue_pages(rbname, start, len)) {
2089 mark_source_rp_bad(ms);
2093 /* Return true to retry, false to quit */
2094 static bool postcopy_pause_return_path_thread(MigrationState *s)
2096 trace_postcopy_pause_return_path();
2098 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2100 trace_postcopy_pause_return_path_continued();
2105 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2107 RAMBlock *block = qemu_ram_block_by_name(block_name);
2110 error_report("%s: invalid block name '%s'", __func__, block_name);
2114 /* Fetch the received bitmap and refresh the dirty bitmap */
2115 return ram_dirty_bitmap_reload(s, block);
2118 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2120 trace_source_return_path_thread_resume_ack(value);
2122 if (value != MIGRATION_RESUME_ACK_VALUE) {
2123 error_report("%s: illegal resume_ack value %"PRIu32,
2128 /* Now both sides are active. */
2129 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2130 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2132 /* Notify send thread that time to continue send pages */
2133 qemu_sem_post(&s->rp_state.rp_sem);
2139 * Handles messages sent on the return path towards the source VM
2142 static void *source_return_path_thread(void *opaque)
2144 MigrationState *ms = opaque;
2145 QEMUFile *rp = ms->rp_state.from_dst_file;
2146 uint16_t header_len, header_type;
2148 uint32_t tmp32, sibling_error;
2149 ram_addr_t start = 0; /* =0 to silence warning */
2150 size_t len = 0, expected_len;
2153 trace_source_return_path_thread_entry();
2154 rcu_register_thread();
2157 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2158 migration_is_setup_or_active(ms->state)) {
2159 trace_source_return_path_thread_loop_top();
2160 header_type = qemu_get_be16(rp);
2161 header_len = qemu_get_be16(rp);
2163 if (qemu_file_get_error(rp)) {
2164 mark_source_rp_bad(ms);
2168 if (header_type >= MIG_RP_MSG_MAX ||
2169 header_type == MIG_RP_MSG_INVALID) {
2170 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2171 header_type, header_len);
2172 mark_source_rp_bad(ms);
2176 if ((rp_cmd_args[header_type].len != -1 &&
2177 header_len != rp_cmd_args[header_type].len) ||
2178 header_len > sizeof(buf)) {
2179 error_report("RP: Received '%s' message (0x%04x) with"
2180 "incorrect length %d expecting %zu",
2181 rp_cmd_args[header_type].name, header_type, header_len,
2182 (size_t)rp_cmd_args[header_type].len);
2183 mark_source_rp_bad(ms);
2187 /* We know we've got a valid header by this point */
2188 res = qemu_get_buffer(rp, buf, header_len);
2189 if (res != header_len) {
2190 error_report("RP: Failed reading data for message 0x%04x"
2191 " read %d expected %d",
2192 header_type, res, header_len);
2193 mark_source_rp_bad(ms);
2197 /* OK, we have the message and the data */
2198 switch (header_type) {
2199 case MIG_RP_MSG_SHUT:
2200 sibling_error = ldl_be_p(buf);
2201 trace_source_return_path_thread_shut(sibling_error);
2202 if (sibling_error) {
2203 error_report("RP: Sibling indicated error %d", sibling_error);
2204 mark_source_rp_bad(ms);
2207 * We'll let the main thread deal with closing the RP
2208 * we could do a shutdown(2) on it, but we're the only user
2209 * anyway, so there's nothing gained.
2213 case MIG_RP_MSG_PONG:
2214 tmp32 = ldl_be_p(buf);
2215 trace_source_return_path_thread_pong(tmp32);
2218 case MIG_RP_MSG_REQ_PAGES:
2219 start = ldq_be_p(buf);
2220 len = ldl_be_p(buf + 8);
2221 migrate_handle_rp_req_pages(ms, NULL, start, len);
2224 case MIG_RP_MSG_REQ_PAGES_ID:
2225 expected_len = 12 + 1; /* header + termination */
2227 if (header_len >= expected_len) {
2228 start = ldq_be_p(buf);
2229 len = ldl_be_p(buf + 8);
2230 /* Now we expect an idstr */
2231 tmp32 = buf[12]; /* Length of the following idstr */
2232 buf[13 + tmp32] = '\0';
2233 expected_len += tmp32;
2235 if (header_len != expected_len) {
2236 error_report("RP: Req_Page_id with length %d expecting %zd",
2237 header_len, expected_len);
2238 mark_source_rp_bad(ms);
2241 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2244 case MIG_RP_MSG_RECV_BITMAP:
2245 if (header_len < 1) {
2246 error_report("%s: missing block name", __func__);
2247 mark_source_rp_bad(ms);
2250 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2251 buf[buf[0] + 1] = '\0';
2252 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2253 mark_source_rp_bad(ms);
2258 case MIG_RP_MSG_RESUME_ACK:
2259 tmp32 = ldl_be_p(buf);
2260 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2261 mark_source_rp_bad(ms);
2272 res = qemu_file_get_error(rp);
2276 * Maybe there is something we can do: it looks like a
2277 * network down issue, and we pause for a recovery.
2279 if (postcopy_pause_return_path_thread(ms)) {
2280 /* Reload rp, reset the rest */
2281 if (rp != ms->rp_state.from_dst_file) {
2283 rp = ms->rp_state.from_dst_file;
2285 ms->rp_state.error = false;
2290 trace_source_return_path_thread_bad_end();
2291 mark_source_rp_bad(ms);
2294 trace_source_return_path_thread_end();
2295 ms->rp_state.from_dst_file = NULL;
2297 rcu_unregister_thread();
2301 static int open_return_path_on_source(MigrationState *ms,
2305 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2306 if (!ms->rp_state.from_dst_file) {
2310 trace_open_return_path_on_source();
2312 if (!create_thread) {
2317 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2318 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2320 trace_open_return_path_on_source_continue();
2325 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2326 static int await_return_path_close_on_source(MigrationState *ms)
2329 * If this is a normal exit then the destination will send a SHUT and the
2330 * rp_thread will exit, however if there's an error we need to cause
2333 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2335 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2336 * waiting for the destination.
2338 qemu_file_shutdown(ms->rp_state.from_dst_file);
2339 mark_source_rp_bad(ms);
2341 trace_await_return_path_close_on_source_joining();
2342 qemu_thread_join(&ms->rp_state.rp_thread);
2343 trace_await_return_path_close_on_source_close();
2344 return ms->rp_state.error;
2348 * Switch from normal iteration to postcopy
2349 * Returns non-0 on error
2351 static int postcopy_start(MigrationState *ms)
2354 QIOChannelBuffer *bioc;
2356 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2357 int64_t bandwidth = migrate_max_postcopy_bandwidth();
2358 bool restart_block = false;
2359 int cur_state = MIGRATION_STATUS_ACTIVE;
2360 if (!migrate_pause_before_switchover()) {
2361 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2362 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2365 trace_postcopy_start();
2366 qemu_mutex_lock_iothread();
2367 trace_postcopy_start_set_run();
2369 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2370 global_state_store();
2371 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2376 ret = migration_maybe_pause(ms, &cur_state,
2377 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2382 ret = bdrv_inactivate_all();
2386 restart_block = true;
2389 * Cause any non-postcopiable, but iterative devices to
2390 * send out their final data.
2392 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2395 * in Finish migrate and with the io-lock held everything should
2396 * be quiet, but we've potentially still got dirty pages and we
2397 * need to tell the destination to throw any pages it's already received
2400 if (migrate_postcopy_ram()) {
2401 if (ram_postcopy_send_discard_bitmap(ms)) {
2402 error_report("postcopy send discard bitmap failed");
2408 * send rest of state - note things that are doing postcopy
2409 * will notice we're in POSTCOPY_ACTIVE and not actually
2410 * wrap their state up here
2412 /* 0 max-postcopy-bandwidth means unlimited */
2414 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2416 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2418 if (migrate_postcopy_ram()) {
2419 /* Ping just for debugging, helps line traces up */
2420 qemu_savevm_send_ping(ms->to_dst_file, 2);
2424 * While loading the device state we may trigger page transfer
2425 * requests and the fd must be free to process those, and thus
2426 * the destination must read the whole device state off the fd before
2427 * it starts processing it. Unfortunately the ad-hoc migration format
2428 * doesn't allow the destination to know the size to read without fully
2429 * parsing it through each devices load-state code (especially the open
2430 * coded devices that use get/put).
2431 * So we wrap the device state up in a package with a length at the start;
2432 * to do this we use a qemu_buf to hold the whole of the device state.
2434 bioc = qio_channel_buffer_new(4096);
2435 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2436 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2437 object_unref(OBJECT(bioc));
2440 * Make sure the receiver can get incoming pages before we send the rest
2443 qemu_savevm_send_postcopy_listen(fb);
2445 qemu_savevm_state_complete_precopy(fb, false, false);
2446 if (migrate_postcopy_ram()) {
2447 qemu_savevm_send_ping(fb, 3);
2450 qemu_savevm_send_postcopy_run(fb);
2452 /* <><> end of stuff going into the package */
2454 /* Last point of recovery; as soon as we send the package the destination
2455 * can open devices and potentially start running.
2456 * Lets just check again we've not got any errors.
2458 ret = qemu_file_get_error(ms->to_dst_file);
2460 error_report("postcopy_start: Migration stream errored (pre package)");
2464 restart_block = false;
2466 /* Now send that blob */
2467 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2472 /* Send a notify to give a chance for anything that needs to happen
2473 * at the transition to postcopy and after the device state; in particular
2474 * spice needs to trigger a transition now
2476 ms->postcopy_after_devices = true;
2477 notifier_list_notify(&migration_state_notifiers, ms);
2479 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2481 qemu_mutex_unlock_iothread();
2483 if (migrate_postcopy_ram()) {
2485 * Although this ping is just for debug, it could potentially be
2486 * used for getting a better measurement of downtime at the source.
2488 qemu_savevm_send_ping(ms->to_dst_file, 4);
2491 if (migrate_release_ram()) {
2492 ram_postcopy_migrated_memory_release(ms);
2495 ret = qemu_file_get_error(ms->to_dst_file);
2497 error_report("postcopy_start: Migration stream errored");
2498 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2499 MIGRATION_STATUS_FAILED);
2507 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2508 MIGRATION_STATUS_FAILED);
2509 if (restart_block) {
2510 /* A failure happened early enough that we know the destination hasn't
2511 * accessed block devices, so we're safe to recover.
2513 Error *local_err = NULL;
2515 bdrv_invalidate_cache_all(&local_err);
2517 error_report_err(local_err);
2520 qemu_mutex_unlock_iothread();
2525 * migration_maybe_pause: Pause if required to by
2526 * migrate_pause_before_switchover called with the iothread locked
2527 * Returns: 0 on success
2529 static int migration_maybe_pause(MigrationState *s,
2530 int *current_active_state,
2533 if (!migrate_pause_before_switchover()) {
2537 /* Since leaving this state is not atomic with posting the semaphore
2538 * it's possible that someone could have issued multiple migrate_continue
2539 * and the semaphore is incorrectly positive at this point;
2540 * the docs say it's undefined to reinit a semaphore that's already
2541 * init'd, so use timedwait to eat up any existing posts.
2543 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2544 /* This block intentionally left blank */
2547 qemu_mutex_unlock_iothread();
2548 migrate_set_state(&s->state, *current_active_state,
2549 MIGRATION_STATUS_PRE_SWITCHOVER);
2550 qemu_sem_wait(&s->pause_sem);
2551 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2553 *current_active_state = new_state;
2554 qemu_mutex_lock_iothread();
2556 return s->state == new_state ? 0 : -EINVAL;
2560 * migration_completion: Used by migration_thread when there's not much left.
2561 * The caller 'breaks' the loop when this returns.
2563 * @s: Current migration state
2565 static void migration_completion(MigrationState *s)
2568 int current_active_state = s->state;
2570 if (s->state == MIGRATION_STATUS_ACTIVE) {
2571 qemu_mutex_lock_iothread();
2572 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2573 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2574 s->vm_was_running = runstate_is_running();
2575 ret = global_state_store();
2578 bool inactivate = !migrate_colo_enabled();
2579 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2581 ret = migration_maybe_pause(s, ¤t_active_state,
2582 MIGRATION_STATUS_DEVICE);
2585 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2586 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2589 if (inactivate && ret >= 0) {
2590 s->block_inactive = true;
2593 qemu_mutex_unlock_iothread();
2598 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2599 trace_migration_completion_postcopy_end();
2601 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2602 trace_migration_completion_postcopy_end_after_complete();
2606 * If rp was opened we must clean up the thread before
2607 * cleaning everything else up (since if there are no failures
2608 * it will wait for the destination to send it's status in
2611 if (s->rp_state.from_dst_file) {
2613 trace_migration_return_path_end_before();
2614 rp_error = await_return_path_close_on_source(s);
2615 trace_migration_return_path_end_after(rp_error);
2617 goto fail_invalidate;
2621 if (qemu_file_get_error(s->to_dst_file)) {
2622 trace_migration_completion_file_err();
2623 goto fail_invalidate;
2626 if (!migrate_colo_enabled()) {
2627 migrate_set_state(&s->state, current_active_state,
2628 MIGRATION_STATUS_COMPLETED);
2634 /* If not doing postcopy, vm_start() will be called: let's regain
2635 * control on images.
2637 if (s->state == MIGRATION_STATUS_ACTIVE ||
2638 s->state == MIGRATION_STATUS_DEVICE) {
2639 Error *local_err = NULL;
2641 qemu_mutex_lock_iothread();
2642 bdrv_invalidate_cache_all(&local_err);
2644 error_report_err(local_err);
2646 s->block_inactive = false;
2648 qemu_mutex_unlock_iothread();
2652 migrate_set_state(&s->state, current_active_state,
2653 MIGRATION_STATUS_FAILED);
2656 bool migrate_colo_enabled(void)
2658 MigrationState *s = migrate_get_current();
2659 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2662 typedef enum MigThrError {
2663 /* No error detected */
2664 MIG_THR_ERR_NONE = 0,
2665 /* Detected error, but resumed successfully */
2666 MIG_THR_ERR_RECOVERED = 1,
2667 /* Detected fatal error, need to exit */
2668 MIG_THR_ERR_FATAL = 2,
2671 static int postcopy_resume_handshake(MigrationState *s)
2673 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2675 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2676 qemu_sem_wait(&s->rp_state.rp_sem);
2679 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2686 /* Return zero if success, or <0 for error */
2687 static int postcopy_do_resume(MigrationState *s)
2692 * Call all the resume_prepare() hooks, so that modules can be
2693 * ready for the migration resume.
2695 ret = qemu_savevm_state_resume_prepare(s);
2697 error_report("%s: resume_prepare() failure detected: %d",
2703 * Last handshake with destination on the resume (destination will
2704 * switch to postcopy-active afterwards)
2706 ret = postcopy_resume_handshake(s);
2708 error_report("%s: handshake failed: %d", __func__, ret);
2716 * We don't return until we are in a safe state to continue current
2717 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2718 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2720 static MigThrError postcopy_pause(MigrationState *s)
2722 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2727 migrate_set_state(&s->state, s->state,
2728 MIGRATION_STATUS_POSTCOPY_PAUSED);
2730 /* Current channel is possibly broken. Release it. */
2731 assert(s->to_dst_file);
2732 qemu_mutex_lock(&s->qemu_file_lock);
2733 file = s->to_dst_file;
2734 s->to_dst_file = NULL;
2735 qemu_mutex_unlock(&s->qemu_file_lock);
2737 qemu_file_shutdown(file);
2740 error_report("Detected IO failure for postcopy. "
2741 "Migration paused.");
2744 * We wait until things fixed up. Then someone will setup the
2745 * status back for us.
2747 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2748 qemu_sem_wait(&s->postcopy_pause_sem);
2751 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2752 /* Woken up by a recover procedure. Give it a shot */
2755 * Firstly, let's wake up the return path now, with a new
2756 * return path channel.
2758 qemu_sem_post(&s->postcopy_pause_rp_sem);
2760 /* Do the resume logic */
2761 if (postcopy_do_resume(s) == 0) {
2762 /* Let's continue! */
2763 trace_postcopy_pause_continued();
2764 return MIG_THR_ERR_RECOVERED;
2767 * Something wrong happened during the recovery, let's
2768 * pause again. Pause is always better than throwing
2774 /* This is not right... Time to quit. */
2775 return MIG_THR_ERR_FATAL;
2780 static MigThrError migration_detect_error(MigrationState *s)
2784 /* Try to detect any file errors */
2785 ret = qemu_file_get_error(s->to_dst_file);
2788 /* Everything is fine */
2789 return MIG_THR_ERR_NONE;
2792 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
2794 * For postcopy, we allow the network to be down for a
2795 * while. After that, it can be continued by a
2798 return postcopy_pause(s);
2801 * For precopy (or postcopy with error outside IO), we fail
2804 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
2805 trace_migration_thread_file_err();
2807 /* Time to stop the migration, now. */
2808 return MIG_THR_ERR_FATAL;
2812 /* How many bytes have we transferred since the beggining of the migration */
2813 static uint64_t migration_total_bytes(MigrationState *s)
2815 return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
2818 static void migration_calculate_complete(MigrationState *s)
2820 uint64_t bytes = migration_total_bytes(s);
2821 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2822 int64_t transfer_time;
2824 s->total_time = end_time - s->start_time;
2827 * It's still not set, so we are precopy migration. For
2828 * postcopy, downtime is calculated during postcopy_start().
2830 s->downtime = end_time - s->downtime_start;
2833 transfer_time = s->total_time - s->setup_time;
2834 if (transfer_time) {
2835 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
2839 static void migration_update_counters(MigrationState *s,
2840 int64_t current_time)
2842 uint64_t transferred, time_spent;
2843 uint64_t current_bytes; /* bytes transferred since the beginning */
2846 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2850 current_bytes = migration_total_bytes(s);
2851 transferred = current_bytes - s->iteration_initial_bytes;
2852 time_spent = current_time - s->iteration_start_time;
2853 bandwidth = (double)transferred / time_spent;
2854 s->threshold_size = bandwidth * s->parameters.downtime_limit;
2856 s->mbps = (((double) transferred * 8.0) /
2857 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2860 * if we haven't sent anything, we don't want to
2861 * recalculate. 10000 is a small enough number for our purposes
2863 if (ram_counters.dirty_pages_rate && transferred > 10000) {
2864 s->expected_downtime = ram_counters.remaining / bandwidth;
2867 qemu_file_reset_rate_limit(s->to_dst_file);
2869 s->iteration_start_time = current_time;
2870 s->iteration_initial_bytes = current_bytes;
2872 trace_migrate_transferred(transferred, time_spent,
2873 bandwidth, s->threshold_size);
2876 /* Migration thread iteration status */
2878 MIG_ITERATE_RESUME, /* Resume current iteration */
2879 MIG_ITERATE_SKIP, /* Skip current iteration */
2880 MIG_ITERATE_BREAK, /* Break the loop */
2884 * Return true if continue to the next iteration directly, false
2887 static MigIterateState migration_iteration_run(MigrationState *s)
2889 uint64_t pending_size, pend_pre, pend_compat, pend_post;
2890 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2892 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2893 &pend_compat, &pend_post);
2894 pending_size = pend_pre + pend_compat + pend_post;
2896 trace_migrate_pending(pending_size, s->threshold_size,
2897 pend_pre, pend_compat, pend_post);
2899 if (pending_size && pending_size >= s->threshold_size) {
2900 /* Still a significant amount to transfer */
2901 if (migrate_postcopy() && !in_postcopy &&
2902 pend_pre <= s->threshold_size &&
2903 atomic_read(&s->start_postcopy)) {
2904 if (postcopy_start(s)) {
2905 error_report("%s: postcopy failed to start", __func__);
2907 return MIG_ITERATE_SKIP;
2909 /* Just another iteration step */
2910 qemu_savevm_state_iterate(s->to_dst_file,
2911 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2913 trace_migration_thread_low_pending(pending_size);
2914 migration_completion(s);
2915 return MIG_ITERATE_BREAK;
2918 return MIG_ITERATE_RESUME;
2921 static void migration_iteration_finish(MigrationState *s)
2923 /* If we enabled cpu throttling for auto-converge, turn it off. */
2924 cpu_throttle_stop();
2926 qemu_mutex_lock_iothread();
2928 case MIGRATION_STATUS_COMPLETED:
2929 migration_calculate_complete(s);
2930 runstate_set(RUN_STATE_POSTMIGRATE);
2933 case MIGRATION_STATUS_ACTIVE:
2935 * We should really assert here, but since it's during
2936 * migration, let's try to reduce the usage of assertions.
2938 if (!migrate_colo_enabled()) {
2939 error_report("%s: critical error: calling COLO code without "
2940 "COLO enabled", __func__);
2942 migrate_start_colo_process(s);
2944 * Fixme: we will run VM in COLO no matter its old running state.
2945 * After exited COLO, we will keep running.
2947 s->vm_was_running = true;
2949 case MIGRATION_STATUS_FAILED:
2950 case MIGRATION_STATUS_CANCELLED:
2951 case MIGRATION_STATUS_CANCELLING:
2952 if (s->vm_was_running) {
2955 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2956 runstate_set(RUN_STATE_POSTMIGRATE);
2962 /* Should not reach here, but if so, forgive the VM. */
2963 error_report("%s: Unknown ending state %d", __func__, s->state);
2966 qemu_bh_schedule(s->cleanup_bh);
2967 qemu_mutex_unlock_iothread();
2970 void migration_make_urgent_request(void)
2972 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
2975 void migration_consume_urgent_request(void)
2977 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
2981 * Master migration thread on the source VM.
2982 * It drives the migration and pumps the data down the outgoing channel.
2984 static void *migration_thread(void *opaque)
2986 MigrationState *s = opaque;
2987 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2988 MigThrError thr_error;
2989 bool urgent = false;
2991 rcu_register_thread();
2993 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2995 qemu_savevm_state_header(s->to_dst_file);
2998 * If we opened the return path, we need to make sure dst has it
3001 if (s->rp_state.from_dst_file) {
3002 /* Now tell the dest that it should open its end so it can reply */
3003 qemu_savevm_send_open_return_path(s->to_dst_file);
3005 /* And do a ping that will make stuff easier to debug */
3006 qemu_savevm_send_ping(s->to_dst_file, 1);
3009 if (migrate_postcopy()) {
3011 * Tell the destination that we *might* want to do postcopy later;
3012 * if the other end can't do postcopy it should fail now, nice and
3015 qemu_savevm_send_postcopy_advise(s->to_dst_file);
3018 qemu_savevm_state_setup(s->to_dst_file);
3020 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3021 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3022 MIGRATION_STATUS_ACTIVE);
3024 trace_migration_thread_setup_complete();
3026 while (s->state == MIGRATION_STATUS_ACTIVE ||
3027 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3028 int64_t current_time;
3030 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3031 MigIterateState iter_state = migration_iteration_run(s);
3032 if (iter_state == MIG_ITERATE_SKIP) {
3034 } else if (iter_state == MIG_ITERATE_BREAK) {
3040 * Try to detect any kind of failures, and see whether we
3041 * should stop the migration now.
3043 thr_error = migration_detect_error(s);
3044 if (thr_error == MIG_THR_ERR_FATAL) {
3045 /* Stop migration */
3047 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3049 * Just recovered from a e.g. network failure, reset all
3050 * the local variables. This is important to avoid
3051 * breaking transferred_bytes and bandwidth calculation
3053 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3054 s->iteration_initial_bytes = 0;
3057 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3059 migration_update_counters(s, current_time);
3062 if (qemu_file_rate_limit(s->to_dst_file)) {
3063 /* Wait for a delay to do rate limiting OR
3064 * something urgent to post the semaphore.
3066 int ms = s->iteration_start_time + BUFFER_DELAY - current_time;
3067 trace_migration_thread_ratelimit_pre(ms);
3068 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3069 /* We were worken by one or more urgent things but
3070 * the timedwait will have consumed one of them.
3071 * The service routine for the urgent wake will dec
3072 * the semaphore itself for each item it consumes,
3073 * so add this one we just eat back.
3075 qemu_sem_post(&s->rate_limit_sem);
3078 trace_migration_thread_ratelimit_post(urgent);
3082 trace_migration_thread_after_loop();
3083 migration_iteration_finish(s);
3084 rcu_unregister_thread();
3088 void migrate_fd_connect(MigrationState *s, Error *error_in)
3091 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3093 s->expected_downtime = s->parameters.downtime_limit;
3094 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
3096 migrate_fd_error(s, error_in);
3097 migrate_fd_cleanup(s);
3102 /* This is a resumed migration */
3103 rate_limit = INT64_MAX;
3105 /* This is a fresh new migration */
3106 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
3108 /* Notify before starting migration thread */
3109 notifier_list_notify(&migration_state_notifiers, s);
3112 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3113 qemu_file_set_blocking(s->to_dst_file, true);
3116 * Open the return path. For postcopy, it is used exclusively. For
3117 * precopy, only if user specified "return-path" capability would
3118 * QEMU uses the return path.
3120 if (migrate_postcopy_ram() || migrate_use_return_path()) {
3121 if (open_return_path_on_source(s, !resume)) {
3122 error_report("Unable to open return-path for postcopy");
3123 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3124 migrate_fd_cleanup(s);
3130 /* Wakeup the main migration thread to do the recovery */
3131 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3132 MIGRATION_STATUS_POSTCOPY_RECOVER);
3133 qemu_sem_post(&s->postcopy_pause_sem);
3137 if (multifd_save_setup() != 0) {
3138 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3139 MIGRATION_STATUS_FAILED);
3140 migrate_fd_cleanup(s);
3143 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
3144 QEMU_THREAD_JOINABLE);
3145 s->migration_thread_running = true;
3148 void migration_global_dump(Monitor *mon)
3150 MigrationState *ms = migrate_get_current();
3152 monitor_printf(mon, "globals:\n");
3153 monitor_printf(mon, "store-global-state: %s\n",
3154 ms->store_global_state ? "on" : "off");
3155 monitor_printf(mon, "only-migratable: %s\n",
3156 ms->only_migratable ? "on" : "off");
3157 monitor_printf(mon, "send-configuration: %s\n",
3158 ms->send_configuration ? "on" : "off");
3159 monitor_printf(mon, "send-section-footer: %s\n",
3160 ms->send_section_footer ? "on" : "off");
3161 monitor_printf(mon, "decompress-error-check: %s\n",
3162 ms->decompress_error_check ? "on" : "off");
3165 #define DEFINE_PROP_MIG_CAP(name, x) \
3166 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3168 static Property migration_properties[] = {
3169 DEFINE_PROP_BOOL("store-global-state", MigrationState,
3170 store_global_state, true),
3171 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
3172 DEFINE_PROP_BOOL("send-configuration", MigrationState,
3173 send_configuration, true),
3174 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3175 send_section_footer, true),
3176 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3177 decompress_error_check, true),
3179 /* Migration parameters */
3180 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
3181 parameters.compress_level,
3182 DEFAULT_MIGRATE_COMPRESS_LEVEL),
3183 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
3184 parameters.compress_threads,
3185 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
3186 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3187 parameters.compress_wait_thread, true),
3188 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
3189 parameters.decompress_threads,
3190 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
3191 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
3192 parameters.cpu_throttle_initial,
3193 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
3194 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
3195 parameters.cpu_throttle_increment,
3196 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
3197 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
3198 parameters.max_bandwidth, MAX_THROTTLE),
3199 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
3200 parameters.downtime_limit,
3201 DEFAULT_MIGRATE_SET_DOWNTIME),
3202 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
3203 parameters.x_checkpoint_delay,
3204 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
3205 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
3206 parameters.x_multifd_channels,
3207 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
3208 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
3209 parameters.x_multifd_page_count,
3210 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
3211 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3212 parameters.xbzrle_cache_size,
3213 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
3214 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3215 parameters.max_postcopy_bandwidth,
3216 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
3217 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3218 parameters.max_cpu_throttle,
3219 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
3221 /* Migration capabilities */
3222 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3223 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3224 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3225 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3226 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3227 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3228 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3229 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3230 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3231 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3232 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
3233 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
3235 DEFINE_PROP_END_OF_LIST(),
3238 static void migration_class_init(ObjectClass *klass, void *data)
3240 DeviceClass *dc = DEVICE_CLASS(klass);
3242 dc->user_creatable = false;
3243 dc->props = migration_properties;
3246 static void migration_instance_finalize(Object *obj)
3248 MigrationState *ms = MIGRATION_OBJ(obj);
3249 MigrationParameters *params = &ms->parameters;
3251 qemu_mutex_destroy(&ms->error_mutex);
3252 qemu_mutex_destroy(&ms->qemu_file_lock);
3253 g_free(params->tls_hostname);
3254 g_free(params->tls_creds);
3255 qemu_sem_destroy(&ms->rate_limit_sem);
3256 qemu_sem_destroy(&ms->pause_sem);
3257 qemu_sem_destroy(&ms->postcopy_pause_sem);
3258 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3259 qemu_sem_destroy(&ms->rp_state.rp_sem);
3260 error_free(ms->error);
3263 static void migration_instance_init(Object *obj)
3265 MigrationState *ms = MIGRATION_OBJ(obj);
3266 MigrationParameters *params = &ms->parameters;
3268 ms->state = MIGRATION_STATUS_NONE;
3270 qemu_sem_init(&ms->pause_sem, 0);
3271 qemu_mutex_init(&ms->error_mutex);
3273 params->tls_hostname = g_strdup("");
3274 params->tls_creds = g_strdup("");
3276 /* Set has_* up only for parameter checks */
3277 params->has_compress_level = true;
3278 params->has_compress_threads = true;
3279 params->has_decompress_threads = true;
3280 params->has_cpu_throttle_initial = true;
3281 params->has_cpu_throttle_increment = true;
3282 params->has_max_bandwidth = true;
3283 params->has_downtime_limit = true;
3284 params->has_x_checkpoint_delay = true;
3285 params->has_block_incremental = true;
3286 params->has_x_multifd_channels = true;
3287 params->has_x_multifd_page_count = true;
3288 params->has_xbzrle_cache_size = true;
3289 params->has_max_postcopy_bandwidth = true;
3290 params->has_max_cpu_throttle = true;
3292 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3293 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3294 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3295 qemu_sem_init(&ms->rate_limit_sem, 0);
3296 qemu_mutex_init(&ms->qemu_file_lock);
3300 * Return true if check pass, false otherwise. Error will be put
3301 * inside errp if provided.
3303 static bool migration_object_check(MigrationState *ms, Error **errp)
3305 MigrationCapabilityStatusList *head = NULL;
3306 /* Assuming all off */
3307 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3310 if (!migrate_params_check(&ms->parameters, errp)) {
3314 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3315 if (ms->enabled_capabilities[i]) {
3316 head = migrate_cap_add(head, i, true);
3320 ret = migrate_caps_check(cap_list, head, errp);
3322 /* It works with head == NULL */
3323 qapi_free_MigrationCapabilityStatusList(head);
3328 static const TypeInfo migration_type = {
3329 .name = TYPE_MIGRATION,
3331 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3332 * not created using qdev_create(), it is not attached to the qdev
3333 * device tree, and it is never realized.
3335 * TODO: Make this TYPE_OBJECT once QOM provides something like
3336 * TYPE_DEVICE's "-global" properties.
3338 .parent = TYPE_DEVICE,
3339 .class_init = migration_class_init,
3340 .class_size = sizeof(MigrationClass),
3341 .instance_size = sizeof(MigrationState),
3342 .instance_init = migration_instance_init,
3343 .instance_finalize = migration_instance_finalize,
3346 static void register_migration_types(void)
3348 type_register_static(&migration_type);
3351 type_init(register_migration_types);