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();
389 Error *local_err = NULL;
391 assert(mis->from_src_file);
392 mis->migration_incoming_co = qemu_coroutine_self();
393 mis->largest_page_size = qemu_ram_pagesize_largest();
394 postcopy_state_set(POSTCOPY_INCOMING_NONE);
395 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
396 MIGRATION_STATUS_ACTIVE);
397 ret = qemu_loadvm_state(mis->from_src_file);
399 ps = postcopy_state_get();
400 trace_process_incoming_migration_co_end(ret, ps);
401 if (ps != POSTCOPY_INCOMING_NONE) {
402 if (ps == POSTCOPY_INCOMING_ADVISE) {
404 * Where a migration had postcopy enabled (and thus went to advise)
405 * but managed to complete within the precopy period, we can use
408 postcopy_ram_incoming_cleanup(mis);
409 } else if (ret >= 0) {
411 * Postcopy was started, cleanup should happen at the end of the
414 trace_process_incoming_migration_co_postcopy_end_main();
417 /* Else if something went wrong then just fall out of the normal exit */
420 /* we get COLO info, and know if we are in COLO mode */
421 if (!ret && migration_incoming_enable_colo()) {
422 /* Make sure all file formats flush their mutable metadata */
423 bdrv_invalidate_cache_all(&local_err);
425 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
426 MIGRATION_STATUS_FAILED);
427 error_report_err(local_err);
431 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
432 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
433 mis->have_colo_incoming_thread = true;
434 qemu_coroutine_yield();
436 /* Wait checkpoint incoming thread exit before free resource */
437 qemu_thread_join(&mis->colo_incoming_thread);
441 Error *local_err = NULL;
443 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
444 MIGRATION_STATUS_FAILED);
445 error_report("load of migration failed: %s", strerror(-ret));
446 qemu_fclose(mis->from_src_file);
447 if (multifd_load_cleanup(&local_err) != 0) {
448 error_report_err(local_err);
452 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
453 qemu_bh_schedule(mis->bh);
454 mis->migration_incoming_co = NULL;
457 static void migration_incoming_setup(QEMUFile *f)
459 MigrationIncomingState *mis = migration_incoming_get_current();
461 if (multifd_load_setup() != 0) {
462 /* We haven't been able to create multifd threads
463 nothing better to do */
467 if (!mis->from_src_file) {
468 mis->from_src_file = f;
470 qemu_file_set_blocking(f, false);
473 void migration_incoming_process(void)
475 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
476 qemu_coroutine_enter(co);
479 /* Returns true if recovered from a paused migration, otherwise false */
480 static bool postcopy_try_recover(QEMUFile *f)
482 MigrationIncomingState *mis = migration_incoming_get_current();
484 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
485 /* Resumed from a paused postcopy migration */
487 mis->from_src_file = f;
488 /* Postcopy has standalone thread to do vm load */
489 qemu_file_set_blocking(f, true);
491 /* Re-configure the return path */
492 mis->to_src_file = qemu_file_get_return_path(f);
494 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
495 MIGRATION_STATUS_POSTCOPY_RECOVER);
498 * Here, we only wake up the main loading thread (while the
499 * fault thread will still be waiting), so that we can receive
500 * commands from source now, and answer it if needed. The
501 * fault thread will be woken up afterwards until we are sure
502 * that source is ready to reply to page requests.
504 qemu_sem_post(&mis->postcopy_pause_sem_dst);
511 void migration_fd_process_incoming(QEMUFile *f)
513 if (postcopy_try_recover(f)) {
517 migration_incoming_setup(f);
518 migration_incoming_process();
521 void migration_ioc_process_incoming(QIOChannel *ioc)
523 MigrationIncomingState *mis = migration_incoming_get_current();
524 bool start_migration;
526 if (!mis->from_src_file) {
527 /* The first connection (multifd may have multiple) */
528 QEMUFile *f = qemu_fopen_channel_input(ioc);
530 /* If it's a recovery, we're done */
531 if (postcopy_try_recover(f)) {
535 migration_incoming_setup(f);
538 * Common migration only needs one channel, so we can start
539 * right now. Multifd needs more than one channel, we wait.
541 start_migration = !migrate_use_multifd();
543 /* Multiple connections */
544 assert(migrate_use_multifd());
545 start_migration = multifd_recv_new_channel(ioc);
548 if (start_migration) {
549 migration_incoming_process();
554 * @migration_has_all_channels: We have received all channels that we need
556 * Returns true when we have got connections to all the channels that
557 * we need for migration.
559 bool migration_has_all_channels(void)
561 MigrationIncomingState *mis = migration_incoming_get_current();
564 all_channels = multifd_recv_all_channels_created();
566 return all_channels && mis->from_src_file != NULL;
570 * Send a 'SHUT' message on the return channel with the given value
571 * to indicate that we've finished with the RP. Non-0 value indicates
574 void migrate_send_rp_shut(MigrationIncomingState *mis,
579 buf = cpu_to_be32(value);
580 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
584 * Send a 'PONG' message on the return channel with the given value
585 * (normally in response to a 'PING')
587 void migrate_send_rp_pong(MigrationIncomingState *mis,
592 buf = cpu_to_be32(value);
593 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
596 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
604 * First, we send the header part. It contains only the len of
605 * idstr, and the idstr itself.
607 len = strlen(block_name);
609 memcpy(buf + 1, block_name, len);
611 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
612 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
617 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
620 * Next, we dump the received bitmap to the stream.
622 * TODO: currently we are safe since we are the only one that is
623 * using the to_src_file handle (fault thread is still paused),
624 * and it's ok even not taking the mutex. However the best way is
625 * to take the lock before sending the message header, and release
626 * the lock after sending the bitmap.
628 qemu_mutex_lock(&mis->rp_mutex);
629 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
630 qemu_mutex_unlock(&mis->rp_mutex);
632 trace_migrate_send_rp_recv_bitmap(block_name, res);
635 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
639 buf = cpu_to_be32(value);
640 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
643 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
645 MigrationCapabilityStatusList *head = NULL;
646 MigrationCapabilityStatusList *caps;
647 MigrationState *s = migrate_get_current();
650 caps = NULL; /* silence compiler warning */
651 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
652 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
653 if (i == MIGRATION_CAPABILITY_BLOCK) {
658 head = g_malloc0(sizeof(*caps));
661 caps->next = g_malloc0(sizeof(*caps));
665 g_malloc(sizeof(*caps->value));
666 caps->value->capability = i;
667 caps->value->state = s->enabled_capabilities[i];
673 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
675 MigrationParameters *params;
676 MigrationState *s = migrate_get_current();
678 /* TODO use QAPI_CLONE() instead of duplicating it inline */
679 params = g_malloc0(sizeof(*params));
680 params->has_compress_level = true;
681 params->compress_level = s->parameters.compress_level;
682 params->has_compress_threads = true;
683 params->compress_threads = s->parameters.compress_threads;
684 params->has_compress_wait_thread = true;
685 params->compress_wait_thread = s->parameters.compress_wait_thread;
686 params->has_decompress_threads = true;
687 params->decompress_threads = s->parameters.decompress_threads;
688 params->has_cpu_throttle_initial = true;
689 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
690 params->has_cpu_throttle_increment = true;
691 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
692 params->has_tls_creds = true;
693 params->tls_creds = g_strdup(s->parameters.tls_creds);
694 params->has_tls_hostname = true;
695 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
696 params->has_max_bandwidth = true;
697 params->max_bandwidth = s->parameters.max_bandwidth;
698 params->has_downtime_limit = true;
699 params->downtime_limit = s->parameters.downtime_limit;
700 params->has_x_checkpoint_delay = true;
701 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
702 params->has_block_incremental = true;
703 params->block_incremental = s->parameters.block_incremental;
704 params->has_x_multifd_channels = true;
705 params->x_multifd_channels = s->parameters.x_multifd_channels;
706 params->has_x_multifd_page_count = true;
707 params->x_multifd_page_count = s->parameters.x_multifd_page_count;
708 params->has_xbzrle_cache_size = true;
709 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
710 params->has_max_postcopy_bandwidth = true;
711 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
712 params->has_max_cpu_throttle = true;
713 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
719 * Return true if we're already in the middle of a migration
720 * (i.e. any of the active or setup states)
722 static bool migration_is_setup_or_active(int state)
725 case MIGRATION_STATUS_ACTIVE:
726 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
727 case MIGRATION_STATUS_POSTCOPY_PAUSED:
728 case MIGRATION_STATUS_POSTCOPY_RECOVER:
729 case MIGRATION_STATUS_SETUP:
730 case MIGRATION_STATUS_PRE_SWITCHOVER:
731 case MIGRATION_STATUS_DEVICE:
740 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
742 info->has_ram = true;
743 info->ram = g_malloc0(sizeof(*info->ram));
744 info->ram->transferred = ram_counters.transferred;
745 info->ram->total = ram_bytes_total();
746 info->ram->duplicate = ram_counters.duplicate;
747 /* legacy value. It is not used anymore */
748 info->ram->skipped = 0;
749 info->ram->normal = ram_counters.normal;
750 info->ram->normal_bytes = ram_counters.normal *
751 qemu_target_page_size();
752 info->ram->mbps = s->mbps;
753 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
754 info->ram->postcopy_requests = ram_counters.postcopy_requests;
755 info->ram->page_size = qemu_target_page_size();
756 info->ram->multifd_bytes = ram_counters.multifd_bytes;
758 if (migrate_use_xbzrle()) {
759 info->has_xbzrle_cache = true;
760 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
761 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
762 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
763 info->xbzrle_cache->pages = xbzrle_counters.pages;
764 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
765 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
766 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
769 if (migrate_use_compression()) {
770 info->has_compression = true;
771 info->compression = g_malloc0(sizeof(*info->compression));
772 info->compression->pages = compression_counters.pages;
773 info->compression->busy = compression_counters.busy;
774 info->compression->busy_rate = compression_counters.busy_rate;
775 info->compression->compressed_size =
776 compression_counters.compressed_size;
777 info->compression->compression_rate =
778 compression_counters.compression_rate;
781 if (cpu_throttle_active()) {
782 info->has_cpu_throttle_percentage = true;
783 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
786 if (s->state != MIGRATION_STATUS_COMPLETED) {
787 info->ram->remaining = ram_bytes_remaining();
788 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
792 static void populate_disk_info(MigrationInfo *info)
794 if (blk_mig_active()) {
795 info->has_disk = true;
796 info->disk = g_malloc0(sizeof(*info->disk));
797 info->disk->transferred = blk_mig_bytes_transferred();
798 info->disk->remaining = blk_mig_bytes_remaining();
799 info->disk->total = blk_mig_bytes_total();
803 static void fill_source_migration_info(MigrationInfo *info)
805 MigrationState *s = migrate_get_current();
808 case MIGRATION_STATUS_NONE:
809 /* no migration has happened ever */
810 /* do not overwrite destination migration status */
813 case MIGRATION_STATUS_SETUP:
814 info->has_status = true;
815 info->has_total_time = false;
817 case MIGRATION_STATUS_ACTIVE:
818 case MIGRATION_STATUS_CANCELLING:
819 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
820 case MIGRATION_STATUS_PRE_SWITCHOVER:
821 case MIGRATION_STATUS_DEVICE:
822 case MIGRATION_STATUS_POSTCOPY_PAUSED:
823 case MIGRATION_STATUS_POSTCOPY_RECOVER:
824 /* TODO add some postcopy stats */
825 info->has_status = true;
826 info->has_total_time = true;
827 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
829 info->has_expected_downtime = true;
830 info->expected_downtime = s->expected_downtime;
831 info->has_setup_time = true;
832 info->setup_time = s->setup_time;
834 populate_ram_info(info, s);
835 populate_disk_info(info);
837 case MIGRATION_STATUS_COLO:
838 info->has_status = true;
839 /* TODO: display COLO specific information (checkpoint info etc.) */
841 case MIGRATION_STATUS_COMPLETED:
842 info->has_status = true;
843 info->has_total_time = true;
844 info->total_time = s->total_time;
845 info->has_downtime = true;
846 info->downtime = s->downtime;
847 info->has_setup_time = true;
848 info->setup_time = s->setup_time;
850 populate_ram_info(info, s);
852 case MIGRATION_STATUS_FAILED:
853 info->has_status = true;
855 info->has_error_desc = true;
856 info->error_desc = g_strdup(error_get_pretty(s->error));
859 case MIGRATION_STATUS_CANCELLED:
860 info->has_status = true;
863 info->status = s->state;
867 * @migration_caps_check - check capability validity
869 * @cap_list: old capability list, array of bool
870 * @params: new capabilities to be applied soon
871 * @errp: set *errp if the check failed, with reason
873 * Returns true if check passed, otherwise false.
875 static bool migrate_caps_check(bool *cap_list,
876 MigrationCapabilityStatusList *params,
879 MigrationCapabilityStatusList *cap;
880 bool old_postcopy_cap;
881 MigrationIncomingState *mis = migration_incoming_get_current();
883 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
885 for (cap = params; cap; cap = cap->next) {
886 cap_list[cap->value->capability] = cap->value->state;
889 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
890 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
891 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
893 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
898 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
899 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
900 /* The decompression threads asynchronously write into RAM
901 * rather than use the atomic copies needed to avoid
902 * userfaulting. It should be possible to fix the decompression
903 * threads for compatibility in future.
905 error_setg(errp, "Postcopy is not currently compatible "
910 /* This check is reasonably expensive, so only when it's being
911 * set the first time, also it's only the destination that needs
914 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
915 !postcopy_ram_supported_by_host(mis)) {
916 /* postcopy_ram_supported_by_host will have emitted a more
919 error_setg(errp, "Postcopy is not supported");
927 static void fill_destination_migration_info(MigrationInfo *info)
929 MigrationIncomingState *mis = migration_incoming_get_current();
931 switch (mis->state) {
932 case MIGRATION_STATUS_NONE:
935 case MIGRATION_STATUS_SETUP:
936 case MIGRATION_STATUS_CANCELLING:
937 case MIGRATION_STATUS_CANCELLED:
938 case MIGRATION_STATUS_ACTIVE:
939 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
940 case MIGRATION_STATUS_POSTCOPY_PAUSED:
941 case MIGRATION_STATUS_POSTCOPY_RECOVER:
942 case MIGRATION_STATUS_FAILED:
943 case MIGRATION_STATUS_COLO:
944 info->has_status = true;
946 case MIGRATION_STATUS_COMPLETED:
947 info->has_status = true;
948 fill_destination_postcopy_migration_info(info);
951 info->status = mis->state;
954 MigrationInfo *qmp_query_migrate(Error **errp)
956 MigrationInfo *info = g_malloc0(sizeof(*info));
958 fill_destination_migration_info(info);
959 fill_source_migration_info(info);
964 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
967 MigrationState *s = migrate_get_current();
968 MigrationCapabilityStatusList *cap;
969 bool cap_list[MIGRATION_CAPABILITY__MAX];
971 if (migration_is_setup_or_active(s->state)) {
972 error_setg(errp, QERR_MIGRATION_ACTIVE);
976 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
977 if (!migrate_caps_check(cap_list, params, errp)) {
981 for (cap = params; cap; cap = cap->next) {
982 s->enabled_capabilities[cap->value->capability] = cap->value->state;
987 * Check whether the parameters are valid. Error will be put into errp
988 * (if provided). Return true if valid, otherwise false.
990 static bool migrate_params_check(MigrationParameters *params, Error **errp)
992 if (params->has_compress_level &&
993 (params->compress_level > 9)) {
994 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
995 "is invalid, it should be in the range of 0 to 9");
999 if (params->has_compress_threads && (params->compress_threads < 1)) {
1000 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1002 "is invalid, it should be in the range of 1 to 255");
1006 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1007 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1008 "decompress_threads",
1009 "is invalid, it should be in the range of 1 to 255");
1013 if (params->has_cpu_throttle_initial &&
1014 (params->cpu_throttle_initial < 1 ||
1015 params->cpu_throttle_initial > 99)) {
1016 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1017 "cpu_throttle_initial",
1018 "an integer in the range of 1 to 99");
1022 if (params->has_cpu_throttle_increment &&
1023 (params->cpu_throttle_increment < 1 ||
1024 params->cpu_throttle_increment > 99)) {
1025 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1026 "cpu_throttle_increment",
1027 "an integer in the range of 1 to 99");
1031 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1032 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
1033 " range of 0 to %zu bytes/second", SIZE_MAX);
1037 if (params->has_downtime_limit &&
1038 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1039 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1040 "the range of 0 to %d milliseconds",
1041 MAX_MIGRATE_DOWNTIME);
1045 /* x_checkpoint_delay is now always positive */
1047 if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
1048 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1050 "is invalid, it should be in the range of 1 to 255");
1053 if (params->has_x_multifd_page_count &&
1054 (params->x_multifd_page_count < 1 ||
1055 params->x_multifd_page_count > 10000)) {
1056 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1057 "multifd_page_count",
1058 "is invalid, it should be in the range of 1 to 10000");
1062 if (params->has_xbzrle_cache_size &&
1063 (params->xbzrle_cache_size < qemu_target_page_size() ||
1064 !is_power_of_2(params->xbzrle_cache_size))) {
1065 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1066 "xbzrle_cache_size",
1067 "is invalid, it should be bigger than target page size"
1068 " and a power of two");
1072 if (params->has_max_cpu_throttle &&
1073 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1074 params->max_cpu_throttle > 99)) {
1075 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1077 "an integer in the range of cpu_throttle_initial to 99");
1084 static void migrate_params_test_apply(MigrateSetParameters *params,
1085 MigrationParameters *dest)
1087 *dest = migrate_get_current()->parameters;
1089 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1091 if (params->has_compress_level) {
1092 dest->compress_level = params->compress_level;
1095 if (params->has_compress_threads) {
1096 dest->compress_threads = params->compress_threads;
1099 if (params->has_compress_wait_thread) {
1100 dest->compress_wait_thread = params->compress_wait_thread;
1103 if (params->has_decompress_threads) {
1104 dest->decompress_threads = params->decompress_threads;
1107 if (params->has_cpu_throttle_initial) {
1108 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1111 if (params->has_cpu_throttle_increment) {
1112 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1115 if (params->has_tls_creds) {
1116 assert(params->tls_creds->type == QTYPE_QSTRING);
1117 dest->tls_creds = g_strdup(params->tls_creds->u.s);
1120 if (params->has_tls_hostname) {
1121 assert(params->tls_hostname->type == QTYPE_QSTRING);
1122 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1125 if (params->has_max_bandwidth) {
1126 dest->max_bandwidth = params->max_bandwidth;
1129 if (params->has_downtime_limit) {
1130 dest->downtime_limit = params->downtime_limit;
1133 if (params->has_x_checkpoint_delay) {
1134 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1137 if (params->has_block_incremental) {
1138 dest->block_incremental = params->block_incremental;
1140 if (params->has_x_multifd_channels) {
1141 dest->x_multifd_channels = params->x_multifd_channels;
1143 if (params->has_x_multifd_page_count) {
1144 dest->x_multifd_page_count = params->x_multifd_page_count;
1146 if (params->has_xbzrle_cache_size) {
1147 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1149 if (params->has_max_postcopy_bandwidth) {
1150 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1152 if (params->has_max_cpu_throttle) {
1153 dest->max_cpu_throttle = params->max_cpu_throttle;
1157 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1159 MigrationState *s = migrate_get_current();
1161 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1163 if (params->has_compress_level) {
1164 s->parameters.compress_level = params->compress_level;
1167 if (params->has_compress_threads) {
1168 s->parameters.compress_threads = params->compress_threads;
1171 if (params->has_compress_wait_thread) {
1172 s->parameters.compress_wait_thread = params->compress_wait_thread;
1175 if (params->has_decompress_threads) {
1176 s->parameters.decompress_threads = params->decompress_threads;
1179 if (params->has_cpu_throttle_initial) {
1180 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1183 if (params->has_cpu_throttle_increment) {
1184 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1187 if (params->has_tls_creds) {
1188 g_free(s->parameters.tls_creds);
1189 assert(params->tls_creds->type == QTYPE_QSTRING);
1190 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1193 if (params->has_tls_hostname) {
1194 g_free(s->parameters.tls_hostname);
1195 assert(params->tls_hostname->type == QTYPE_QSTRING);
1196 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1199 if (params->has_max_bandwidth) {
1200 s->parameters.max_bandwidth = params->max_bandwidth;
1201 if (s->to_dst_file) {
1202 qemu_file_set_rate_limit(s->to_dst_file,
1203 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1207 if (params->has_downtime_limit) {
1208 s->parameters.downtime_limit = params->downtime_limit;
1211 if (params->has_x_checkpoint_delay) {
1212 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1213 if (migration_in_colo_state()) {
1214 colo_checkpoint_notify(s);
1218 if (params->has_block_incremental) {
1219 s->parameters.block_incremental = params->block_incremental;
1221 if (params->has_x_multifd_channels) {
1222 s->parameters.x_multifd_channels = params->x_multifd_channels;
1224 if (params->has_x_multifd_page_count) {
1225 s->parameters.x_multifd_page_count = params->x_multifd_page_count;
1227 if (params->has_xbzrle_cache_size) {
1228 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1229 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1231 if (params->has_max_postcopy_bandwidth) {
1232 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1234 if (params->has_max_cpu_throttle) {
1235 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1239 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1241 MigrationParameters tmp;
1243 /* TODO Rewrite "" to null instead */
1244 if (params->has_tls_creds
1245 && params->tls_creds->type == QTYPE_QNULL) {
1246 qobject_unref(params->tls_creds->u.n);
1247 params->tls_creds->type = QTYPE_QSTRING;
1248 params->tls_creds->u.s = strdup("");
1250 /* TODO Rewrite "" to null instead */
1251 if (params->has_tls_hostname
1252 && params->tls_hostname->type == QTYPE_QNULL) {
1253 qobject_unref(params->tls_hostname->u.n);
1254 params->tls_hostname->type = QTYPE_QSTRING;
1255 params->tls_hostname->u.s = strdup("");
1258 migrate_params_test_apply(params, &tmp);
1260 if (!migrate_params_check(&tmp, errp)) {
1261 /* Invalid parameter */
1265 migrate_params_apply(params, errp);
1269 void qmp_migrate_start_postcopy(Error **errp)
1271 MigrationState *s = migrate_get_current();
1273 if (!migrate_postcopy()) {
1274 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1275 " the start of migration");
1279 if (s->state == MIGRATION_STATUS_NONE) {
1280 error_setg(errp, "Postcopy must be started after migration has been"
1285 * we don't error if migration has finished since that would be racy
1286 * with issuing this command.
1288 atomic_set(&s->start_postcopy, true);
1291 /* shared migration helpers */
1293 void migrate_set_state(int *state, int old_state, int new_state)
1295 assert(new_state < MIGRATION_STATUS__MAX);
1296 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1297 trace_migrate_set_state(MigrationStatus_str(new_state));
1298 migrate_generate_event(new_state);
1302 static MigrationCapabilityStatusList *migrate_cap_add(
1303 MigrationCapabilityStatusList *list,
1304 MigrationCapability index,
1307 MigrationCapabilityStatusList *cap;
1309 cap = g_new0(MigrationCapabilityStatusList, 1);
1310 cap->value = g_new0(MigrationCapabilityStatus, 1);
1311 cap->value->capability = index;
1312 cap->value->state = state;
1318 void migrate_set_block_enabled(bool value, Error **errp)
1320 MigrationCapabilityStatusList *cap;
1322 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1323 qmp_migrate_set_capabilities(cap, errp);
1324 qapi_free_MigrationCapabilityStatusList(cap);
1327 static void migrate_set_block_incremental(MigrationState *s, bool value)
1329 s->parameters.block_incremental = value;
1332 static void block_cleanup_parameters(MigrationState *s)
1334 if (s->must_remove_block_options) {
1335 /* setting to false can never fail */
1336 migrate_set_block_enabled(false, &error_abort);
1337 migrate_set_block_incremental(s, false);
1338 s->must_remove_block_options = false;
1342 static void migrate_fd_cleanup(void *opaque)
1344 MigrationState *s = opaque;
1346 qemu_bh_delete(s->cleanup_bh);
1347 s->cleanup_bh = NULL;
1349 qemu_savevm_state_cleanup();
1351 if (s->to_dst_file) {
1352 Error *local_err = NULL;
1355 trace_migrate_fd_cleanup();
1356 qemu_mutex_unlock_iothread();
1357 if (s->migration_thread_running) {
1358 qemu_thread_join(&s->thread);
1359 s->migration_thread_running = false;
1361 qemu_mutex_lock_iothread();
1363 if (multifd_save_cleanup(&local_err) != 0) {
1364 error_report_err(local_err);
1366 qemu_mutex_lock(&s->qemu_file_lock);
1367 tmp = s->to_dst_file;
1368 s->to_dst_file = NULL;
1369 qemu_mutex_unlock(&s->qemu_file_lock);
1371 * Close the file handle without the lock to make sure the
1372 * critical section won't block for long.
1377 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1378 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
1380 if (s->state == MIGRATION_STATUS_CANCELLING) {
1381 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1382 MIGRATION_STATUS_CANCELLED);
1386 /* It is used on info migrate. We can't free it */
1387 error_report_err(error_copy(s->error));
1389 notifier_list_notify(&migration_state_notifiers, s);
1390 block_cleanup_parameters(s);
1393 void migrate_set_error(MigrationState *s, const Error *error)
1395 qemu_mutex_lock(&s->error_mutex);
1397 s->error = error_copy(error);
1399 qemu_mutex_unlock(&s->error_mutex);
1402 void migrate_fd_error(MigrationState *s, const Error *error)
1404 trace_migrate_fd_error(error_get_pretty(error));
1405 assert(s->to_dst_file == NULL);
1406 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1407 MIGRATION_STATUS_FAILED);
1408 migrate_set_error(s, error);
1411 static void migrate_fd_cancel(MigrationState *s)
1414 QEMUFile *f = migrate_get_current()->to_dst_file;
1415 trace_migrate_fd_cancel();
1417 if (s->rp_state.from_dst_file) {
1418 /* shutdown the rp socket, so causing the rp thread to shutdown */
1419 qemu_file_shutdown(s->rp_state.from_dst_file);
1423 old_state = s->state;
1424 if (!migration_is_setup_or_active(old_state)) {
1427 /* If the migration is paused, kick it out of the pause */
1428 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1429 qemu_sem_post(&s->pause_sem);
1431 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1432 } while (s->state != MIGRATION_STATUS_CANCELLING);
1435 * If we're unlucky the migration code might be stuck somewhere in a
1436 * send/write while the network has failed and is waiting to timeout;
1437 * if we've got shutdown(2) available then we can force it to quit.
1438 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1439 * called in a bh, so there is no race against this cancel.
1441 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1442 qemu_file_shutdown(f);
1444 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1445 Error *local_err = NULL;
1447 bdrv_invalidate_cache_all(&local_err);
1449 error_report_err(local_err);
1451 s->block_inactive = false;
1456 void add_migration_state_change_notifier(Notifier *notify)
1458 notifier_list_add(&migration_state_notifiers, notify);
1461 void remove_migration_state_change_notifier(Notifier *notify)
1463 notifier_remove(notify);
1466 bool migration_in_setup(MigrationState *s)
1468 return s->state == MIGRATION_STATUS_SETUP;
1471 bool migration_has_finished(MigrationState *s)
1473 return s->state == MIGRATION_STATUS_COMPLETED;
1476 bool migration_has_failed(MigrationState *s)
1478 return (s->state == MIGRATION_STATUS_CANCELLED ||
1479 s->state == MIGRATION_STATUS_FAILED);
1482 bool migration_in_postcopy(void)
1484 MigrationState *s = migrate_get_current();
1486 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1489 bool migration_in_postcopy_after_devices(MigrationState *s)
1491 return migration_in_postcopy() && s->postcopy_after_devices;
1494 bool migration_is_idle(void)
1496 MigrationState *s = migrate_get_current();
1499 case MIGRATION_STATUS_NONE:
1500 case MIGRATION_STATUS_CANCELLED:
1501 case MIGRATION_STATUS_COMPLETED:
1502 case MIGRATION_STATUS_FAILED:
1504 case MIGRATION_STATUS_SETUP:
1505 case MIGRATION_STATUS_CANCELLING:
1506 case MIGRATION_STATUS_ACTIVE:
1507 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1508 case MIGRATION_STATUS_COLO:
1509 case MIGRATION_STATUS_PRE_SWITCHOVER:
1510 case MIGRATION_STATUS_DEVICE:
1512 case MIGRATION_STATUS__MAX:
1513 g_assert_not_reached();
1519 void migrate_init(MigrationState *s)
1522 * Reinitialise all migration state, except
1523 * parameters/capabilities that the user set, and
1529 s->to_dst_file = NULL;
1530 s->state = MIGRATION_STATUS_NONE;
1531 s->rp_state.from_dst_file = NULL;
1532 s->rp_state.error = false;
1535 s->expected_downtime = 0;
1537 s->start_postcopy = false;
1538 s->postcopy_after_devices = false;
1539 s->migration_thread_running = false;
1540 error_free(s->error);
1543 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1545 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1547 s->vm_was_running = false;
1548 s->iteration_initial_bytes = 0;
1549 s->threshold_size = 0;
1552 static GSList *migration_blockers;
1554 int migrate_add_blocker(Error *reason, Error **errp)
1556 if (migrate_get_current()->only_migratable) {
1557 error_propagate(errp, error_copy(reason));
1558 error_prepend(errp, "disallowing migration blocker "
1559 "(--only_migratable) for: ");
1563 if (migration_is_idle()) {
1564 migration_blockers = g_slist_prepend(migration_blockers, reason);
1568 error_propagate(errp, error_copy(reason));
1569 error_prepend(errp, "disallowing migration blocker (migration in "
1574 void migrate_del_blocker(Error *reason)
1576 migration_blockers = g_slist_remove(migration_blockers, reason);
1579 void qmp_migrate_incoming(const char *uri, Error **errp)
1581 Error *local_err = NULL;
1582 static bool once = true;
1584 if (!deferred_incoming) {
1585 error_setg(errp, "For use with '-incoming defer'");
1589 error_setg(errp, "The incoming migration has already been started");
1592 qemu_start_incoming_migration(uri, &local_err);
1595 error_propagate(errp, local_err);
1602 void qmp_migrate_recover(const char *uri, Error **errp)
1604 MigrationIncomingState *mis = migration_incoming_get_current();
1606 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1607 error_setg(errp, "Migrate recover can only be run "
1608 "when postcopy is paused.");
1612 if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1613 false, true) == true) {
1614 error_setg(errp, "Migrate recovery is triggered already");
1619 * Note that this call will never start a real migration; it will
1620 * only re-setup the migration stream and poke existing migration
1621 * to continue using that newly established channel.
1623 qemu_start_incoming_migration(uri, errp);
1626 void qmp_migrate_pause(Error **errp)
1628 MigrationState *ms = migrate_get_current();
1629 MigrationIncomingState *mis = migration_incoming_get_current();
1632 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1633 /* Source side, during postcopy */
1634 qemu_mutex_lock(&ms->qemu_file_lock);
1635 ret = qemu_file_shutdown(ms->to_dst_file);
1636 qemu_mutex_unlock(&ms->qemu_file_lock);
1638 error_setg(errp, "Failed to pause source migration");
1643 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1644 ret = qemu_file_shutdown(mis->from_src_file);
1646 error_setg(errp, "Failed to pause destination migration");
1651 error_setg(errp, "migrate-pause is currently only supported "
1652 "during postcopy-active state");
1655 bool migration_is_blocked(Error **errp)
1657 if (qemu_savevm_state_blocked(errp)) {
1661 if (migration_blockers) {
1662 error_propagate(errp, error_copy(migration_blockers->data));
1669 /* Returns true if continue to migrate, or false if error detected */
1670 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1671 bool resume, Error **errp)
1673 Error *local_err = NULL;
1676 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1677 error_setg(errp, "Cannot resume if there is no "
1678 "paused migration");
1683 * Postcopy recovery won't work well with release-ram
1684 * capability since release-ram will drop the page buffer as
1685 * long as the page is put into the send buffer. So if there
1686 * is a network failure happened, any page buffers that have
1687 * not yet reached the destination VM but have already been
1688 * sent from the source VM will be lost forever. Let's refuse
1689 * the client from resuming such a postcopy migration.
1690 * Luckily release-ram was designed to only be used when src
1691 * and destination VMs are on the same host, so it should be
1694 if (migrate_release_ram()) {
1695 error_setg(errp, "Postcopy recovery cannot work "
1696 "when release-ram capability is set");
1700 /* This is a resume, skip init status */
1704 if (migration_is_setup_or_active(s->state) ||
1705 s->state == MIGRATION_STATUS_CANCELLING ||
1706 s->state == MIGRATION_STATUS_COLO) {
1707 error_setg(errp, QERR_MIGRATION_ACTIVE);
1711 if (runstate_check(RUN_STATE_INMIGRATE)) {
1712 error_setg(errp, "Guest is waiting for an incoming migration");
1716 if (migration_is_blocked(errp)) {
1720 if (blk || blk_inc) {
1721 if (migrate_use_block() || migrate_use_block_incremental()) {
1722 error_setg(errp, "Command options are incompatible with "
1723 "current migration capabilities");
1726 migrate_set_block_enabled(true, &local_err);
1728 error_propagate(errp, local_err);
1731 s->must_remove_block_options = true;
1735 migrate_set_block_incremental(s, true);
1743 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1744 bool has_inc, bool inc, bool has_detach, bool detach,
1745 bool has_resume, bool resume, Error **errp)
1747 Error *local_err = NULL;
1748 MigrationState *s = migrate_get_current();
1751 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1752 has_resume && resume, errp)) {
1753 /* Error detected, put into errp */
1757 if (strstart(uri, "tcp:", &p)) {
1758 tcp_start_outgoing_migration(s, p, &local_err);
1760 } else if (strstart(uri, "rdma:", &p)) {
1761 rdma_start_outgoing_migration(s, p, &local_err);
1763 } else if (strstart(uri, "exec:", &p)) {
1764 exec_start_outgoing_migration(s, p, &local_err);
1765 } else if (strstart(uri, "unix:", &p)) {
1766 unix_start_outgoing_migration(s, p, &local_err);
1767 } else if (strstart(uri, "fd:", &p)) {
1768 fd_start_outgoing_migration(s, p, &local_err);
1770 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1771 "a valid migration protocol");
1772 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1773 MIGRATION_STATUS_FAILED);
1774 block_cleanup_parameters(s);
1779 migrate_fd_error(s, local_err);
1780 error_propagate(errp, local_err);
1785 void qmp_migrate_cancel(Error **errp)
1787 migrate_fd_cancel(migrate_get_current());
1790 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1792 MigrationState *s = migrate_get_current();
1793 if (s->state != state) {
1794 error_setg(errp, "Migration not in expected state: %s",
1795 MigrationStatus_str(s->state));
1798 qemu_sem_post(&s->pause_sem);
1801 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1803 MigrateSetParameters p = {
1804 .has_xbzrle_cache_size = true,
1805 .xbzrle_cache_size = value,
1808 qmp_migrate_set_parameters(&p, errp);
1811 int64_t qmp_query_migrate_cache_size(Error **errp)
1813 return migrate_xbzrle_cache_size();
1816 void qmp_migrate_set_speed(int64_t value, Error **errp)
1818 MigrateSetParameters p = {
1819 .has_max_bandwidth = true,
1820 .max_bandwidth = value,
1823 qmp_migrate_set_parameters(&p, errp);
1826 void qmp_migrate_set_downtime(double value, Error **errp)
1828 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1829 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1830 "the range of 0 to %d seconds",
1831 MAX_MIGRATE_DOWNTIME_SECONDS);
1835 value *= 1000; /* Convert to milliseconds */
1836 value = MAX(0, MIN(INT64_MAX, value));
1838 MigrateSetParameters p = {
1839 .has_downtime_limit = true,
1840 .downtime_limit = value,
1843 qmp_migrate_set_parameters(&p, errp);
1846 bool migrate_release_ram(void)
1850 s = migrate_get_current();
1852 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1855 bool migrate_postcopy_ram(void)
1859 s = migrate_get_current();
1861 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1864 bool migrate_postcopy(void)
1866 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1869 bool migrate_auto_converge(void)
1873 s = migrate_get_current();
1875 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1878 bool migrate_zero_blocks(void)
1882 s = migrate_get_current();
1884 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1887 bool migrate_postcopy_blocktime(void)
1891 s = migrate_get_current();
1893 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
1896 bool migrate_use_compression(void)
1900 s = migrate_get_current();
1902 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1905 int migrate_compress_level(void)
1909 s = migrate_get_current();
1911 return s->parameters.compress_level;
1914 int migrate_compress_threads(void)
1918 s = migrate_get_current();
1920 return s->parameters.compress_threads;
1923 int migrate_compress_wait_thread(void)
1927 s = migrate_get_current();
1929 return s->parameters.compress_wait_thread;
1932 int migrate_decompress_threads(void)
1936 s = migrate_get_current();
1938 return s->parameters.decompress_threads;
1941 bool migrate_dirty_bitmaps(void)
1945 s = migrate_get_current();
1947 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1950 bool migrate_use_events(void)
1954 s = migrate_get_current();
1956 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1959 bool migrate_use_multifd(void)
1963 s = migrate_get_current();
1965 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1968 bool migrate_pause_before_switchover(void)
1972 s = migrate_get_current();
1974 return s->enabled_capabilities[
1975 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1978 int migrate_multifd_channels(void)
1982 s = migrate_get_current();
1984 return s->parameters.x_multifd_channels;
1987 int migrate_multifd_page_count(void)
1991 s = migrate_get_current();
1993 return s->parameters.x_multifd_page_count;
1996 int migrate_use_xbzrle(void)
2000 s = migrate_get_current();
2002 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2005 int64_t migrate_xbzrle_cache_size(void)
2009 s = migrate_get_current();
2011 return s->parameters.xbzrle_cache_size;
2014 static int64_t migrate_max_postcopy_bandwidth(void)
2018 s = migrate_get_current();
2020 return s->parameters.max_postcopy_bandwidth;
2023 bool migrate_use_block(void)
2027 s = migrate_get_current();
2029 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2032 bool migrate_use_return_path(void)
2036 s = migrate_get_current();
2038 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2041 bool migrate_use_block_incremental(void)
2045 s = migrate_get_current();
2047 return s->parameters.block_incremental;
2050 /* migration thread support */
2052 * Something bad happened to the RP stream, mark an error
2053 * The caller shall print or trace something to indicate why
2055 static void mark_source_rp_bad(MigrationState *s)
2057 s->rp_state.error = true;
2060 static struct rp_cmd_args {
2061 ssize_t len; /* -1 = variable */
2064 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2065 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2066 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2067 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2068 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2069 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2070 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2071 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2075 * Process a request for pages received on the return path,
2076 * We're allowed to send more than requested (e.g. to round to our page size)
2077 * and we don't need to send pages that have already been sent.
2079 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2080 ram_addr_t start, size_t len)
2082 long our_host_ps = getpagesize();
2084 trace_migrate_handle_rp_req_pages(rbname, start, len);
2087 * Since we currently insist on matching page sizes, just sanity check
2088 * we're being asked for whole host pages.
2090 if (start & (our_host_ps-1) ||
2091 (len & (our_host_ps-1))) {
2092 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2093 " len: %zd", __func__, start, len);
2094 mark_source_rp_bad(ms);
2098 if (ram_save_queue_pages(rbname, start, len)) {
2099 mark_source_rp_bad(ms);
2103 /* Return true to retry, false to quit */
2104 static bool postcopy_pause_return_path_thread(MigrationState *s)
2106 trace_postcopy_pause_return_path();
2108 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2110 trace_postcopy_pause_return_path_continued();
2115 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2117 RAMBlock *block = qemu_ram_block_by_name(block_name);
2120 error_report("%s: invalid block name '%s'", __func__, block_name);
2124 /* Fetch the received bitmap and refresh the dirty bitmap */
2125 return ram_dirty_bitmap_reload(s, block);
2128 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2130 trace_source_return_path_thread_resume_ack(value);
2132 if (value != MIGRATION_RESUME_ACK_VALUE) {
2133 error_report("%s: illegal resume_ack value %"PRIu32,
2138 /* Now both sides are active. */
2139 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2140 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2142 /* Notify send thread that time to continue send pages */
2143 qemu_sem_post(&s->rp_state.rp_sem);
2149 * Handles messages sent on the return path towards the source VM
2152 static void *source_return_path_thread(void *opaque)
2154 MigrationState *ms = opaque;
2155 QEMUFile *rp = ms->rp_state.from_dst_file;
2156 uint16_t header_len, header_type;
2158 uint32_t tmp32, sibling_error;
2159 ram_addr_t start = 0; /* =0 to silence warning */
2160 size_t len = 0, expected_len;
2163 trace_source_return_path_thread_entry();
2164 rcu_register_thread();
2167 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2168 migration_is_setup_or_active(ms->state)) {
2169 trace_source_return_path_thread_loop_top();
2170 header_type = qemu_get_be16(rp);
2171 header_len = qemu_get_be16(rp);
2173 if (qemu_file_get_error(rp)) {
2174 mark_source_rp_bad(ms);
2178 if (header_type >= MIG_RP_MSG_MAX ||
2179 header_type == MIG_RP_MSG_INVALID) {
2180 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2181 header_type, header_len);
2182 mark_source_rp_bad(ms);
2186 if ((rp_cmd_args[header_type].len != -1 &&
2187 header_len != rp_cmd_args[header_type].len) ||
2188 header_len > sizeof(buf)) {
2189 error_report("RP: Received '%s' message (0x%04x) with"
2190 "incorrect length %d expecting %zu",
2191 rp_cmd_args[header_type].name, header_type, header_len,
2192 (size_t)rp_cmd_args[header_type].len);
2193 mark_source_rp_bad(ms);
2197 /* We know we've got a valid header by this point */
2198 res = qemu_get_buffer(rp, buf, header_len);
2199 if (res != header_len) {
2200 error_report("RP: Failed reading data for message 0x%04x"
2201 " read %d expected %d",
2202 header_type, res, header_len);
2203 mark_source_rp_bad(ms);
2207 /* OK, we have the message and the data */
2208 switch (header_type) {
2209 case MIG_RP_MSG_SHUT:
2210 sibling_error = ldl_be_p(buf);
2211 trace_source_return_path_thread_shut(sibling_error);
2212 if (sibling_error) {
2213 error_report("RP: Sibling indicated error %d", sibling_error);
2214 mark_source_rp_bad(ms);
2217 * We'll let the main thread deal with closing the RP
2218 * we could do a shutdown(2) on it, but we're the only user
2219 * anyway, so there's nothing gained.
2223 case MIG_RP_MSG_PONG:
2224 tmp32 = ldl_be_p(buf);
2225 trace_source_return_path_thread_pong(tmp32);
2228 case MIG_RP_MSG_REQ_PAGES:
2229 start = ldq_be_p(buf);
2230 len = ldl_be_p(buf + 8);
2231 migrate_handle_rp_req_pages(ms, NULL, start, len);
2234 case MIG_RP_MSG_REQ_PAGES_ID:
2235 expected_len = 12 + 1; /* header + termination */
2237 if (header_len >= expected_len) {
2238 start = ldq_be_p(buf);
2239 len = ldl_be_p(buf + 8);
2240 /* Now we expect an idstr */
2241 tmp32 = buf[12]; /* Length of the following idstr */
2242 buf[13 + tmp32] = '\0';
2243 expected_len += tmp32;
2245 if (header_len != expected_len) {
2246 error_report("RP: Req_Page_id with length %d expecting %zd",
2247 header_len, expected_len);
2248 mark_source_rp_bad(ms);
2251 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2254 case MIG_RP_MSG_RECV_BITMAP:
2255 if (header_len < 1) {
2256 error_report("%s: missing block name", __func__);
2257 mark_source_rp_bad(ms);
2260 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2261 buf[buf[0] + 1] = '\0';
2262 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2263 mark_source_rp_bad(ms);
2268 case MIG_RP_MSG_RESUME_ACK:
2269 tmp32 = ldl_be_p(buf);
2270 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2271 mark_source_rp_bad(ms);
2282 res = qemu_file_get_error(rp);
2286 * Maybe there is something we can do: it looks like a
2287 * network down issue, and we pause for a recovery.
2289 if (postcopy_pause_return_path_thread(ms)) {
2290 /* Reload rp, reset the rest */
2291 if (rp != ms->rp_state.from_dst_file) {
2293 rp = ms->rp_state.from_dst_file;
2295 ms->rp_state.error = false;
2300 trace_source_return_path_thread_bad_end();
2301 mark_source_rp_bad(ms);
2304 trace_source_return_path_thread_end();
2305 ms->rp_state.from_dst_file = NULL;
2307 rcu_unregister_thread();
2311 static int open_return_path_on_source(MigrationState *ms,
2315 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2316 if (!ms->rp_state.from_dst_file) {
2320 trace_open_return_path_on_source();
2322 if (!create_thread) {
2327 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2328 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2330 trace_open_return_path_on_source_continue();
2335 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2336 static int await_return_path_close_on_source(MigrationState *ms)
2339 * If this is a normal exit then the destination will send a SHUT and the
2340 * rp_thread will exit, however if there's an error we need to cause
2343 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2345 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2346 * waiting for the destination.
2348 qemu_file_shutdown(ms->rp_state.from_dst_file);
2349 mark_source_rp_bad(ms);
2351 trace_await_return_path_close_on_source_joining();
2352 qemu_thread_join(&ms->rp_state.rp_thread);
2353 trace_await_return_path_close_on_source_close();
2354 return ms->rp_state.error;
2358 * Switch from normal iteration to postcopy
2359 * Returns non-0 on error
2361 static int postcopy_start(MigrationState *ms)
2364 QIOChannelBuffer *bioc;
2366 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2367 int64_t bandwidth = migrate_max_postcopy_bandwidth();
2368 bool restart_block = false;
2369 int cur_state = MIGRATION_STATUS_ACTIVE;
2370 if (!migrate_pause_before_switchover()) {
2371 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2372 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2375 trace_postcopy_start();
2376 qemu_mutex_lock_iothread();
2377 trace_postcopy_start_set_run();
2379 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2380 global_state_store();
2381 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2386 ret = migration_maybe_pause(ms, &cur_state,
2387 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2392 ret = bdrv_inactivate_all();
2396 restart_block = true;
2399 * Cause any non-postcopiable, but iterative devices to
2400 * send out their final data.
2402 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2405 * in Finish migrate and with the io-lock held everything should
2406 * be quiet, but we've potentially still got dirty pages and we
2407 * need to tell the destination to throw any pages it's already received
2410 if (migrate_postcopy_ram()) {
2411 if (ram_postcopy_send_discard_bitmap(ms)) {
2412 error_report("postcopy send discard bitmap failed");
2418 * send rest of state - note things that are doing postcopy
2419 * will notice we're in POSTCOPY_ACTIVE and not actually
2420 * wrap their state up here
2422 /* 0 max-postcopy-bandwidth means unlimited */
2424 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2426 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2428 if (migrate_postcopy_ram()) {
2429 /* Ping just for debugging, helps line traces up */
2430 qemu_savevm_send_ping(ms->to_dst_file, 2);
2434 * While loading the device state we may trigger page transfer
2435 * requests and the fd must be free to process those, and thus
2436 * the destination must read the whole device state off the fd before
2437 * it starts processing it. Unfortunately the ad-hoc migration format
2438 * doesn't allow the destination to know the size to read without fully
2439 * parsing it through each devices load-state code (especially the open
2440 * coded devices that use get/put).
2441 * So we wrap the device state up in a package with a length at the start;
2442 * to do this we use a qemu_buf to hold the whole of the device state.
2444 bioc = qio_channel_buffer_new(4096);
2445 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2446 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2447 object_unref(OBJECT(bioc));
2450 * Make sure the receiver can get incoming pages before we send the rest
2453 qemu_savevm_send_postcopy_listen(fb);
2455 qemu_savevm_state_complete_precopy(fb, false, false);
2456 if (migrate_postcopy_ram()) {
2457 qemu_savevm_send_ping(fb, 3);
2460 qemu_savevm_send_postcopy_run(fb);
2462 /* <><> end of stuff going into the package */
2464 /* Last point of recovery; as soon as we send the package the destination
2465 * can open devices and potentially start running.
2466 * Lets just check again we've not got any errors.
2468 ret = qemu_file_get_error(ms->to_dst_file);
2470 error_report("postcopy_start: Migration stream errored (pre package)");
2474 restart_block = false;
2476 /* Now send that blob */
2477 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2482 /* Send a notify to give a chance for anything that needs to happen
2483 * at the transition to postcopy and after the device state; in particular
2484 * spice needs to trigger a transition now
2486 ms->postcopy_after_devices = true;
2487 notifier_list_notify(&migration_state_notifiers, ms);
2489 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2491 qemu_mutex_unlock_iothread();
2493 if (migrate_postcopy_ram()) {
2495 * Although this ping is just for debug, it could potentially be
2496 * used for getting a better measurement of downtime at the source.
2498 qemu_savevm_send_ping(ms->to_dst_file, 4);
2501 if (migrate_release_ram()) {
2502 ram_postcopy_migrated_memory_release(ms);
2505 ret = qemu_file_get_error(ms->to_dst_file);
2507 error_report("postcopy_start: Migration stream errored");
2508 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2509 MIGRATION_STATUS_FAILED);
2517 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2518 MIGRATION_STATUS_FAILED);
2519 if (restart_block) {
2520 /* A failure happened early enough that we know the destination hasn't
2521 * accessed block devices, so we're safe to recover.
2523 Error *local_err = NULL;
2525 bdrv_invalidate_cache_all(&local_err);
2527 error_report_err(local_err);
2530 qemu_mutex_unlock_iothread();
2535 * migration_maybe_pause: Pause if required to by
2536 * migrate_pause_before_switchover called with the iothread locked
2537 * Returns: 0 on success
2539 static int migration_maybe_pause(MigrationState *s,
2540 int *current_active_state,
2543 if (!migrate_pause_before_switchover()) {
2547 /* Since leaving this state is not atomic with posting the semaphore
2548 * it's possible that someone could have issued multiple migrate_continue
2549 * and the semaphore is incorrectly positive at this point;
2550 * the docs say it's undefined to reinit a semaphore that's already
2551 * init'd, so use timedwait to eat up any existing posts.
2553 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2554 /* This block intentionally left blank */
2557 qemu_mutex_unlock_iothread();
2558 migrate_set_state(&s->state, *current_active_state,
2559 MIGRATION_STATUS_PRE_SWITCHOVER);
2560 qemu_sem_wait(&s->pause_sem);
2561 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2563 *current_active_state = new_state;
2564 qemu_mutex_lock_iothread();
2566 return s->state == new_state ? 0 : -EINVAL;
2570 * migration_completion: Used by migration_thread when there's not much left.
2571 * The caller 'breaks' the loop when this returns.
2573 * @s: Current migration state
2575 static void migration_completion(MigrationState *s)
2578 int current_active_state = s->state;
2580 if (s->state == MIGRATION_STATUS_ACTIVE) {
2581 qemu_mutex_lock_iothread();
2582 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2583 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2584 s->vm_was_running = runstate_is_running();
2585 ret = global_state_store();
2588 bool inactivate = !migrate_colo_enabled();
2589 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2591 ret = migration_maybe_pause(s, ¤t_active_state,
2592 MIGRATION_STATUS_DEVICE);
2595 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2596 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2599 if (inactivate && ret >= 0) {
2600 s->block_inactive = true;
2603 qemu_mutex_unlock_iothread();
2608 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2609 trace_migration_completion_postcopy_end();
2611 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2612 trace_migration_completion_postcopy_end_after_complete();
2616 * If rp was opened we must clean up the thread before
2617 * cleaning everything else up (since if there are no failures
2618 * it will wait for the destination to send it's status in
2621 if (s->rp_state.from_dst_file) {
2623 trace_migration_return_path_end_before();
2624 rp_error = await_return_path_close_on_source(s);
2625 trace_migration_return_path_end_after(rp_error);
2627 goto fail_invalidate;
2631 if (qemu_file_get_error(s->to_dst_file)) {
2632 trace_migration_completion_file_err();
2633 goto fail_invalidate;
2636 if (!migrate_colo_enabled()) {
2637 migrate_set_state(&s->state, current_active_state,
2638 MIGRATION_STATUS_COMPLETED);
2644 /* If not doing postcopy, vm_start() will be called: let's regain
2645 * control on images.
2647 if (s->state == MIGRATION_STATUS_ACTIVE ||
2648 s->state == MIGRATION_STATUS_DEVICE) {
2649 Error *local_err = NULL;
2651 qemu_mutex_lock_iothread();
2652 bdrv_invalidate_cache_all(&local_err);
2654 error_report_err(local_err);
2656 s->block_inactive = false;
2658 qemu_mutex_unlock_iothread();
2662 migrate_set_state(&s->state, current_active_state,
2663 MIGRATION_STATUS_FAILED);
2666 bool migrate_colo_enabled(void)
2668 MigrationState *s = migrate_get_current();
2669 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2672 typedef enum MigThrError {
2673 /* No error detected */
2674 MIG_THR_ERR_NONE = 0,
2675 /* Detected error, but resumed successfully */
2676 MIG_THR_ERR_RECOVERED = 1,
2677 /* Detected fatal error, need to exit */
2678 MIG_THR_ERR_FATAL = 2,
2681 static int postcopy_resume_handshake(MigrationState *s)
2683 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2685 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2686 qemu_sem_wait(&s->rp_state.rp_sem);
2689 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2696 /* Return zero if success, or <0 for error */
2697 static int postcopy_do_resume(MigrationState *s)
2702 * Call all the resume_prepare() hooks, so that modules can be
2703 * ready for the migration resume.
2705 ret = qemu_savevm_state_resume_prepare(s);
2707 error_report("%s: resume_prepare() failure detected: %d",
2713 * Last handshake with destination on the resume (destination will
2714 * switch to postcopy-active afterwards)
2716 ret = postcopy_resume_handshake(s);
2718 error_report("%s: handshake failed: %d", __func__, ret);
2726 * We don't return until we are in a safe state to continue current
2727 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2728 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2730 static MigThrError postcopy_pause(MigrationState *s)
2732 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2737 migrate_set_state(&s->state, s->state,
2738 MIGRATION_STATUS_POSTCOPY_PAUSED);
2740 /* Current channel is possibly broken. Release it. */
2741 assert(s->to_dst_file);
2742 qemu_mutex_lock(&s->qemu_file_lock);
2743 file = s->to_dst_file;
2744 s->to_dst_file = NULL;
2745 qemu_mutex_unlock(&s->qemu_file_lock);
2747 qemu_file_shutdown(file);
2750 error_report("Detected IO failure for postcopy. "
2751 "Migration paused.");
2754 * We wait until things fixed up. Then someone will setup the
2755 * status back for us.
2757 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2758 qemu_sem_wait(&s->postcopy_pause_sem);
2761 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2762 /* Woken up by a recover procedure. Give it a shot */
2765 * Firstly, let's wake up the return path now, with a new
2766 * return path channel.
2768 qemu_sem_post(&s->postcopy_pause_rp_sem);
2770 /* Do the resume logic */
2771 if (postcopy_do_resume(s) == 0) {
2772 /* Let's continue! */
2773 trace_postcopy_pause_continued();
2774 return MIG_THR_ERR_RECOVERED;
2777 * Something wrong happened during the recovery, let's
2778 * pause again. Pause is always better than throwing
2784 /* This is not right... Time to quit. */
2785 return MIG_THR_ERR_FATAL;
2790 static MigThrError migration_detect_error(MigrationState *s)
2794 /* Try to detect any file errors */
2795 ret = qemu_file_get_error(s->to_dst_file);
2798 /* Everything is fine */
2799 return MIG_THR_ERR_NONE;
2802 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
2804 * For postcopy, we allow the network to be down for a
2805 * while. After that, it can be continued by a
2808 return postcopy_pause(s);
2811 * For precopy (or postcopy with error outside IO), we fail
2814 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
2815 trace_migration_thread_file_err();
2817 /* Time to stop the migration, now. */
2818 return MIG_THR_ERR_FATAL;
2822 /* How many bytes have we transferred since the beggining of the migration */
2823 static uint64_t migration_total_bytes(MigrationState *s)
2825 return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
2828 static void migration_calculate_complete(MigrationState *s)
2830 uint64_t bytes = migration_total_bytes(s);
2831 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2832 int64_t transfer_time;
2834 s->total_time = end_time - s->start_time;
2837 * It's still not set, so we are precopy migration. For
2838 * postcopy, downtime is calculated during postcopy_start().
2840 s->downtime = end_time - s->downtime_start;
2843 transfer_time = s->total_time - s->setup_time;
2844 if (transfer_time) {
2845 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
2849 static void migration_update_counters(MigrationState *s,
2850 int64_t current_time)
2852 uint64_t transferred, time_spent;
2853 uint64_t current_bytes; /* bytes transferred since the beginning */
2856 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2860 current_bytes = migration_total_bytes(s);
2861 transferred = current_bytes - s->iteration_initial_bytes;
2862 time_spent = current_time - s->iteration_start_time;
2863 bandwidth = (double)transferred / time_spent;
2864 s->threshold_size = bandwidth * s->parameters.downtime_limit;
2866 s->mbps = (((double) transferred * 8.0) /
2867 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2870 * if we haven't sent anything, we don't want to
2871 * recalculate. 10000 is a small enough number for our purposes
2873 if (ram_counters.dirty_pages_rate && transferred > 10000) {
2874 s->expected_downtime = ram_counters.remaining / bandwidth;
2877 qemu_file_reset_rate_limit(s->to_dst_file);
2879 s->iteration_start_time = current_time;
2880 s->iteration_initial_bytes = current_bytes;
2882 trace_migrate_transferred(transferred, time_spent,
2883 bandwidth, s->threshold_size);
2886 /* Migration thread iteration status */
2888 MIG_ITERATE_RESUME, /* Resume current iteration */
2889 MIG_ITERATE_SKIP, /* Skip current iteration */
2890 MIG_ITERATE_BREAK, /* Break the loop */
2894 * Return true if continue to the next iteration directly, false
2897 static MigIterateState migration_iteration_run(MigrationState *s)
2899 uint64_t pending_size, pend_pre, pend_compat, pend_post;
2900 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2902 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2903 &pend_compat, &pend_post);
2904 pending_size = pend_pre + pend_compat + pend_post;
2906 trace_migrate_pending(pending_size, s->threshold_size,
2907 pend_pre, pend_compat, pend_post);
2909 if (pending_size && pending_size >= s->threshold_size) {
2910 /* Still a significant amount to transfer */
2911 if (migrate_postcopy() && !in_postcopy &&
2912 pend_pre <= s->threshold_size &&
2913 atomic_read(&s->start_postcopy)) {
2914 if (postcopy_start(s)) {
2915 error_report("%s: postcopy failed to start", __func__);
2917 return MIG_ITERATE_SKIP;
2919 /* Just another iteration step */
2920 qemu_savevm_state_iterate(s->to_dst_file,
2921 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2923 trace_migration_thread_low_pending(pending_size);
2924 migration_completion(s);
2925 return MIG_ITERATE_BREAK;
2928 return MIG_ITERATE_RESUME;
2931 static void migration_iteration_finish(MigrationState *s)
2933 /* If we enabled cpu throttling for auto-converge, turn it off. */
2934 cpu_throttle_stop();
2936 qemu_mutex_lock_iothread();
2938 case MIGRATION_STATUS_COMPLETED:
2939 migration_calculate_complete(s);
2940 runstate_set(RUN_STATE_POSTMIGRATE);
2943 case MIGRATION_STATUS_ACTIVE:
2945 * We should really assert here, but since it's during
2946 * migration, let's try to reduce the usage of assertions.
2948 if (!migrate_colo_enabled()) {
2949 error_report("%s: critical error: calling COLO code without "
2950 "COLO enabled", __func__);
2952 migrate_start_colo_process(s);
2954 * Fixme: we will run VM in COLO no matter its old running state.
2955 * After exited COLO, we will keep running.
2957 s->vm_was_running = true;
2959 case MIGRATION_STATUS_FAILED:
2960 case MIGRATION_STATUS_CANCELLED:
2961 case MIGRATION_STATUS_CANCELLING:
2962 if (s->vm_was_running) {
2965 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2966 runstate_set(RUN_STATE_POSTMIGRATE);
2972 /* Should not reach here, but if so, forgive the VM. */
2973 error_report("%s: Unknown ending state %d", __func__, s->state);
2976 qemu_bh_schedule(s->cleanup_bh);
2977 qemu_mutex_unlock_iothread();
2980 void migration_make_urgent_request(void)
2982 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
2985 void migration_consume_urgent_request(void)
2987 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
2991 * Master migration thread on the source VM.
2992 * It drives the migration and pumps the data down the outgoing channel.
2994 static void *migration_thread(void *opaque)
2996 MigrationState *s = opaque;
2997 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2998 MigThrError thr_error;
2999 bool urgent = false;
3001 rcu_register_thread();
3003 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3005 qemu_savevm_state_header(s->to_dst_file);
3008 * If we opened the return path, we need to make sure dst has it
3011 if (s->rp_state.from_dst_file) {
3012 /* Now tell the dest that it should open its end so it can reply */
3013 qemu_savevm_send_open_return_path(s->to_dst_file);
3015 /* And do a ping that will make stuff easier to debug */
3016 qemu_savevm_send_ping(s->to_dst_file, 1);
3019 if (migrate_postcopy()) {
3021 * Tell the destination that we *might* want to do postcopy later;
3022 * if the other end can't do postcopy it should fail now, nice and
3025 qemu_savevm_send_postcopy_advise(s->to_dst_file);
3028 qemu_savevm_state_setup(s->to_dst_file);
3030 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3031 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3032 MIGRATION_STATUS_ACTIVE);
3034 trace_migration_thread_setup_complete();
3036 while (s->state == MIGRATION_STATUS_ACTIVE ||
3037 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3038 int64_t current_time;
3040 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3041 MigIterateState iter_state = migration_iteration_run(s);
3042 if (iter_state == MIG_ITERATE_SKIP) {
3044 } else if (iter_state == MIG_ITERATE_BREAK) {
3050 * Try to detect any kind of failures, and see whether we
3051 * should stop the migration now.
3053 thr_error = migration_detect_error(s);
3054 if (thr_error == MIG_THR_ERR_FATAL) {
3055 /* Stop migration */
3057 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3059 * Just recovered from a e.g. network failure, reset all
3060 * the local variables. This is important to avoid
3061 * breaking transferred_bytes and bandwidth calculation
3063 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3064 s->iteration_initial_bytes = 0;
3067 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3069 migration_update_counters(s, current_time);
3072 if (qemu_file_rate_limit(s->to_dst_file)) {
3073 /* Wait for a delay to do rate limiting OR
3074 * something urgent to post the semaphore.
3076 int ms = s->iteration_start_time + BUFFER_DELAY - current_time;
3077 trace_migration_thread_ratelimit_pre(ms);
3078 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3079 /* We were worken by one or more urgent things but
3080 * the timedwait will have consumed one of them.
3081 * The service routine for the urgent wake will dec
3082 * the semaphore itself for each item it consumes,
3083 * so add this one we just eat back.
3085 qemu_sem_post(&s->rate_limit_sem);
3088 trace_migration_thread_ratelimit_post(urgent);
3092 trace_migration_thread_after_loop();
3093 migration_iteration_finish(s);
3094 rcu_unregister_thread();
3098 void migrate_fd_connect(MigrationState *s, Error *error_in)
3101 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3103 s->expected_downtime = s->parameters.downtime_limit;
3104 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
3106 migrate_fd_error(s, error_in);
3107 migrate_fd_cleanup(s);
3112 /* This is a resumed migration */
3113 rate_limit = INT64_MAX;
3115 /* This is a fresh new migration */
3116 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
3118 /* Notify before starting migration thread */
3119 notifier_list_notify(&migration_state_notifiers, s);
3122 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3123 qemu_file_set_blocking(s->to_dst_file, true);
3126 * Open the return path. For postcopy, it is used exclusively. For
3127 * precopy, only if user specified "return-path" capability would
3128 * QEMU uses the return path.
3130 if (migrate_postcopy_ram() || migrate_use_return_path()) {
3131 if (open_return_path_on_source(s, !resume)) {
3132 error_report("Unable to open return-path for postcopy");
3133 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3134 migrate_fd_cleanup(s);
3140 /* Wakeup the main migration thread to do the recovery */
3141 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3142 MIGRATION_STATUS_POSTCOPY_RECOVER);
3143 qemu_sem_post(&s->postcopy_pause_sem);
3147 if (multifd_save_setup() != 0) {
3148 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3149 MIGRATION_STATUS_FAILED);
3150 migrate_fd_cleanup(s);
3153 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
3154 QEMU_THREAD_JOINABLE);
3155 s->migration_thread_running = true;
3158 void migration_global_dump(Monitor *mon)
3160 MigrationState *ms = migrate_get_current();
3162 monitor_printf(mon, "globals:\n");
3163 monitor_printf(mon, "store-global-state: %s\n",
3164 ms->store_global_state ? "on" : "off");
3165 monitor_printf(mon, "only-migratable: %s\n",
3166 ms->only_migratable ? "on" : "off");
3167 monitor_printf(mon, "send-configuration: %s\n",
3168 ms->send_configuration ? "on" : "off");
3169 monitor_printf(mon, "send-section-footer: %s\n",
3170 ms->send_section_footer ? "on" : "off");
3171 monitor_printf(mon, "decompress-error-check: %s\n",
3172 ms->decompress_error_check ? "on" : "off");
3175 #define DEFINE_PROP_MIG_CAP(name, x) \
3176 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3178 static Property migration_properties[] = {
3179 DEFINE_PROP_BOOL("store-global-state", MigrationState,
3180 store_global_state, true),
3181 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
3182 DEFINE_PROP_BOOL("send-configuration", MigrationState,
3183 send_configuration, true),
3184 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3185 send_section_footer, true),
3186 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3187 decompress_error_check, true),
3189 /* Migration parameters */
3190 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
3191 parameters.compress_level,
3192 DEFAULT_MIGRATE_COMPRESS_LEVEL),
3193 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
3194 parameters.compress_threads,
3195 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
3196 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3197 parameters.compress_wait_thread, true),
3198 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
3199 parameters.decompress_threads,
3200 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
3201 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
3202 parameters.cpu_throttle_initial,
3203 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
3204 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
3205 parameters.cpu_throttle_increment,
3206 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
3207 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
3208 parameters.max_bandwidth, MAX_THROTTLE),
3209 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
3210 parameters.downtime_limit,
3211 DEFAULT_MIGRATE_SET_DOWNTIME),
3212 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
3213 parameters.x_checkpoint_delay,
3214 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
3215 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
3216 parameters.x_multifd_channels,
3217 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
3218 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
3219 parameters.x_multifd_page_count,
3220 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
3221 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3222 parameters.xbzrle_cache_size,
3223 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
3224 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3225 parameters.max_postcopy_bandwidth,
3226 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
3227 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3228 parameters.max_cpu_throttle,
3229 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
3231 /* Migration capabilities */
3232 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3233 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3234 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3235 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3236 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3237 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3238 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3239 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3240 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3241 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3242 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
3243 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
3245 DEFINE_PROP_END_OF_LIST(),
3248 static void migration_class_init(ObjectClass *klass, void *data)
3250 DeviceClass *dc = DEVICE_CLASS(klass);
3252 dc->user_creatable = false;
3253 dc->props = migration_properties;
3256 static void migration_instance_finalize(Object *obj)
3258 MigrationState *ms = MIGRATION_OBJ(obj);
3259 MigrationParameters *params = &ms->parameters;
3261 qemu_mutex_destroy(&ms->error_mutex);
3262 qemu_mutex_destroy(&ms->qemu_file_lock);
3263 g_free(params->tls_hostname);
3264 g_free(params->tls_creds);
3265 qemu_sem_destroy(&ms->rate_limit_sem);
3266 qemu_sem_destroy(&ms->pause_sem);
3267 qemu_sem_destroy(&ms->postcopy_pause_sem);
3268 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3269 qemu_sem_destroy(&ms->rp_state.rp_sem);
3270 error_free(ms->error);
3273 static void migration_instance_init(Object *obj)
3275 MigrationState *ms = MIGRATION_OBJ(obj);
3276 MigrationParameters *params = &ms->parameters;
3278 ms->state = MIGRATION_STATUS_NONE;
3280 qemu_sem_init(&ms->pause_sem, 0);
3281 qemu_mutex_init(&ms->error_mutex);
3283 params->tls_hostname = g_strdup("");
3284 params->tls_creds = g_strdup("");
3286 /* Set has_* up only for parameter checks */
3287 params->has_compress_level = true;
3288 params->has_compress_threads = true;
3289 params->has_decompress_threads = true;
3290 params->has_cpu_throttle_initial = true;
3291 params->has_cpu_throttle_increment = true;
3292 params->has_max_bandwidth = true;
3293 params->has_downtime_limit = true;
3294 params->has_x_checkpoint_delay = true;
3295 params->has_block_incremental = true;
3296 params->has_x_multifd_channels = true;
3297 params->has_x_multifd_page_count = true;
3298 params->has_xbzrle_cache_size = true;
3299 params->has_max_postcopy_bandwidth = true;
3300 params->has_max_cpu_throttle = true;
3302 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3303 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3304 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3305 qemu_sem_init(&ms->rate_limit_sem, 0);
3306 qemu_mutex_init(&ms->qemu_file_lock);
3310 * Return true if check pass, false otherwise. Error will be put
3311 * inside errp if provided.
3313 static bool migration_object_check(MigrationState *ms, Error **errp)
3315 MigrationCapabilityStatusList *head = NULL;
3316 /* Assuming all off */
3317 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3320 if (!migrate_params_check(&ms->parameters, errp)) {
3324 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3325 if (ms->enabled_capabilities[i]) {
3326 head = migrate_cap_add(head, i, true);
3330 ret = migrate_caps_check(cap_list, head, errp);
3332 /* It works with head == NULL */
3333 qapi_free_MigrationCapabilityStatusList(head);
3338 static const TypeInfo migration_type = {
3339 .name = TYPE_MIGRATION,
3341 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3342 * not created using qdev_create(), it is not attached to the qdev
3343 * device tree, and it is never realized.
3345 * TODO: Make this TYPE_OBJECT once QOM provides something like
3346 * TYPE_DEVICE's "-global" properties.
3348 .parent = TYPE_DEVICE,
3349 .class_init = migration_class_init,
3350 .class_size = sizeof(MigrationClass),
3351 .instance_size = sizeof(MigrationState),
3352 .instance_init = migration_instance_init,
3353 .instance_finalize = migration_instance_finalize,
3356 static void register_migration_types(void)
3358 type_register_static(&migration_type);
3361 type_init(register_migration_types);