4 * Copyright IBM, Corp. 2008
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "migration/blocker.h"
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
75 /* Migration XBZRLE default cache size */
76 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
78 /* The delay time (in ms) between two COLO checkpoints
79 * Note: Please change this default value to 10000 when we support hybrid mode.
81 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
82 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
83 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
85 static NotifierList migration_state_notifiers
=
86 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
88 static bool deferred_incoming
;
90 /* Messages sent on the return path from destination to source */
91 enum mig_rp_message_type
{
92 MIG_RP_MSG_INVALID
= 0, /* Must be 0 */
93 MIG_RP_MSG_SHUT
, /* sibling will not send any more RP messages */
94 MIG_RP_MSG_PONG
, /* Response to a PING; data (seq: be32 ) */
96 MIG_RP_MSG_REQ_PAGES_ID
, /* data (start: be64, len: be32, id: string) */
97 MIG_RP_MSG_REQ_PAGES
, /* data (start: be64, len: be32) */
102 /* When we add fault tolerance, we could have several
103 migrations at once. For now we don't need to add
104 dynamic creation of migration */
106 static MigrationState
*current_migration
;
108 static bool migration_object_check(MigrationState
*ms
, Error
**errp
);
109 static int migration_maybe_pause(MigrationState
*s
,
110 int *current_active_state
,
113 void migration_object_init(void)
115 MachineState
*ms
= MACHINE(qdev_get_machine());
118 /* This can only be called once. */
119 assert(!current_migration
);
120 current_migration
= MIGRATION_OBJ(object_new(TYPE_MIGRATION
));
122 if (!migration_object_check(current_migration
, &err
)) {
123 error_report_err(err
);
128 * We cannot really do this in migration_instance_init() since at
129 * that time global properties are not yet applied, then this
130 * value will be definitely replaced by something else.
132 if (ms
->enforce_config_section
) {
133 current_migration
->send_configuration
= true;
137 void migration_object_finalize(void)
139 object_unref(OBJECT(current_migration
));
143 MigrationState
*migrate_get_current(void)
145 /* This can only be called after the object created. */
146 assert(current_migration
);
147 return current_migration
;
150 MigrationIncomingState
*migration_incoming_get_current(void)
153 static MigrationIncomingState mis_current
;
156 mis_current
.state
= MIGRATION_STATUS_NONE
;
157 memset(&mis_current
, 0, sizeof(MigrationIncomingState
));
158 mis_current
.postcopy_remote_fds
= g_array_new(FALSE
, TRUE
,
159 sizeof(struct PostCopyFD
));
160 qemu_mutex_init(&mis_current
.rp_mutex
);
161 qemu_event_init(&mis_current
.main_thread_load_event
, false);
162 qemu_sem_init(&mis_current
.postcopy_pause_sem_dst
, 0);
164 init_dirty_bitmap_incoming_migration();
171 void migration_incoming_state_destroy(void)
173 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
175 if (mis
->to_src_file
) {
176 /* Tell source that we are done */
177 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
178 qemu_fclose(mis
->to_src_file
);
179 mis
->to_src_file
= NULL
;
182 if (mis
->from_src_file
) {
183 qemu_fclose(mis
->from_src_file
);
184 mis
->from_src_file
= NULL
;
186 if (mis
->postcopy_remote_fds
) {
187 g_array_free(mis
->postcopy_remote_fds
, TRUE
);
188 mis
->postcopy_remote_fds
= NULL
;
191 qemu_event_reset(&mis
->main_thread_load_event
);
194 static void migrate_generate_event(int new_state
)
196 if (migrate_use_events()) {
197 qapi_event_send_migration(new_state
, &error_abort
);
202 * Called on -incoming with a defer: uri.
203 * The migration can be started later after any parameters have been
206 static void deferred_incoming_migration(Error
**errp
)
208 if (deferred_incoming
) {
209 error_setg(errp
, "Incoming migration already deferred");
211 deferred_incoming
= true;
215 * Send a message on the return channel back to the source
218 static int migrate_send_rp_message(MigrationIncomingState
*mis
,
219 enum mig_rp_message_type message_type
,
220 uint16_t len
, void *data
)
224 trace_migrate_send_rp_message((int)message_type
, len
);
225 qemu_mutex_lock(&mis
->rp_mutex
);
228 * It's possible that the file handle got lost due to network
231 if (!mis
->to_src_file
) {
236 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
237 qemu_put_be16(mis
->to_src_file
, len
);
238 qemu_put_buffer(mis
->to_src_file
, data
, len
);
239 qemu_fflush(mis
->to_src_file
);
241 /* It's possible that qemu file got error during sending */
242 ret
= qemu_file_get_error(mis
->to_src_file
);
245 qemu_mutex_unlock(&mis
->rp_mutex
);
249 /* Request a range of pages from the source VM at the given
251 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
252 * as the last request (a name must have been given previously)
253 * Start: Address offset within the RB
254 * Len: Length in bytes required - must be a multiple of pagesize
256 int migrate_send_rp_req_pages(MigrationIncomingState
*mis
, const char *rbname
,
257 ram_addr_t start
, size_t len
)
259 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
260 size_t msglen
= 12; /* start + len */
261 enum mig_rp_message_type msg_type
;
263 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
264 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
267 int rbname_len
= strlen(rbname
);
268 assert(rbname_len
< 256);
270 bufc
[msglen
++] = rbname_len
;
271 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
272 msglen
+= rbname_len
;
273 msg_type
= MIG_RP_MSG_REQ_PAGES_ID
;
275 msg_type
= MIG_RP_MSG_REQ_PAGES
;
278 return migrate_send_rp_message(mis
, msg_type
, msglen
, bufc
);
281 void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
285 qapi_event_send_migration(MIGRATION_STATUS_SETUP
, &error_abort
);
286 if (!strcmp(uri
, "defer")) {
287 deferred_incoming_migration(errp
);
288 } else if (strstart(uri
, "tcp:", &p
)) {
289 tcp_start_incoming_migration(p
, errp
);
291 } else if (strstart(uri
, "rdma:", &p
)) {
292 rdma_start_incoming_migration(p
, errp
);
294 } else if (strstart(uri
, "exec:", &p
)) {
295 exec_start_incoming_migration(p
, errp
);
296 } else if (strstart(uri
, "unix:", &p
)) {
297 unix_start_incoming_migration(p
, errp
);
298 } else if (strstart(uri
, "fd:", &p
)) {
299 fd_start_incoming_migration(p
, errp
);
301 error_setg(errp
, "unknown migration protocol: %s", uri
);
305 static void process_incoming_migration_bh(void *opaque
)
307 Error
*local_err
= NULL
;
308 MigrationIncomingState
*mis
= opaque
;
310 /* Make sure all file formats flush their mutable metadata.
311 * If we get an error here, just don't restart the VM yet. */
312 bdrv_invalidate_cache_all(&local_err
);
314 error_report_err(local_err
);
320 * This must happen after all error conditions are dealt with and
321 * we're sure the VM is going to be running on this host.
323 qemu_announce_self();
325 if (multifd_load_cleanup(&local_err
) != 0) {
326 error_report_err(local_err
);
329 /* If global state section was not received or we are in running
330 state, we need to obey autostart. Any other state is set with
333 dirty_bitmap_mig_before_vm_start();
335 if (!global_state_received() ||
336 global_state_get_runstate() == RUN_STATE_RUNNING
) {
340 runstate_set(RUN_STATE_PAUSED
);
343 runstate_set(global_state_get_runstate());
346 * This must happen after any state changes since as soon as an external
347 * observer sees this event they might start to prod at the VM assuming
350 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
351 MIGRATION_STATUS_COMPLETED
);
352 qemu_bh_delete(mis
->bh
);
353 migration_incoming_state_destroy();
356 static void process_incoming_migration_co(void *opaque
)
358 MigrationIncomingState
*mis
= migration_incoming_get_current();
362 assert(mis
->from_src_file
);
363 mis
->largest_page_size
= qemu_ram_pagesize_largest();
364 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
365 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
366 MIGRATION_STATUS_ACTIVE
);
367 ret
= qemu_loadvm_state(mis
->from_src_file
);
369 ps
= postcopy_state_get();
370 trace_process_incoming_migration_co_end(ret
, ps
);
371 if (ps
!= POSTCOPY_INCOMING_NONE
) {
372 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
374 * Where a migration had postcopy enabled (and thus went to advise)
375 * but managed to complete within the precopy period, we can use
378 postcopy_ram_incoming_cleanup(mis
);
379 } else if (ret
>= 0) {
381 * Postcopy was started, cleanup should happen at the end of the
384 trace_process_incoming_migration_co_postcopy_end_main();
387 /* Else if something went wrong then just fall out of the normal exit */
390 /* we get COLO info, and know if we are in COLO mode */
391 if (!ret
&& migration_incoming_enable_colo()) {
392 mis
->migration_incoming_co
= qemu_coroutine_self();
393 qemu_thread_create(&mis
->colo_incoming_thread
, "COLO incoming",
394 colo_process_incoming_thread
, mis
, QEMU_THREAD_JOINABLE
);
395 mis
->have_colo_incoming_thread
= true;
396 qemu_coroutine_yield();
398 /* Wait checkpoint incoming thread exit before free resource */
399 qemu_thread_join(&mis
->colo_incoming_thread
);
403 Error
*local_err
= NULL
;
405 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
406 MIGRATION_STATUS_FAILED
);
407 error_report("load of migration failed: %s", strerror(-ret
));
408 qemu_fclose(mis
->from_src_file
);
409 if (multifd_load_cleanup(&local_err
) != 0) {
410 error_report_err(local_err
);
414 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
415 qemu_bh_schedule(mis
->bh
);
418 static void migration_incoming_setup(QEMUFile
*f
)
420 MigrationIncomingState
*mis
= migration_incoming_get_current();
422 if (multifd_load_setup() != 0) {
423 /* We haven't been able to create multifd threads
424 nothing better to do */
428 if (!mis
->from_src_file
) {
429 mis
->from_src_file
= f
;
431 qemu_file_set_blocking(f
, false);
434 void migration_incoming_process(void)
436 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
437 qemu_coroutine_enter(co
);
440 void migration_fd_process_incoming(QEMUFile
*f
)
442 migration_incoming_setup(f
);
443 migration_incoming_process();
446 void migration_ioc_process_incoming(QIOChannel
*ioc
)
448 MigrationIncomingState
*mis
= migration_incoming_get_current();
450 if (!mis
->from_src_file
) {
451 QEMUFile
*f
= qemu_fopen_channel_input(ioc
);
452 migration_incoming_setup(f
);
455 multifd_recv_new_channel(ioc
);
459 * @migration_has_all_channels: We have received all channels that we need
461 * Returns true when we have got connections to all the channels that
462 * we need for migration.
464 bool migration_has_all_channels(void)
468 all_channels
= multifd_recv_all_channels_created();
474 * Send a 'SHUT' message on the return channel with the given value
475 * to indicate that we've finished with the RP. Non-0 value indicates
478 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
483 buf
= cpu_to_be32(value
);
484 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
488 * Send a 'PONG' message on the return channel with the given value
489 * (normally in response to a 'PING')
491 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
496 buf
= cpu_to_be32(value
);
497 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
500 MigrationCapabilityStatusList
*qmp_query_migrate_capabilities(Error
**errp
)
502 MigrationCapabilityStatusList
*head
= NULL
;
503 MigrationCapabilityStatusList
*caps
;
504 MigrationState
*s
= migrate_get_current();
507 caps
= NULL
; /* silence compiler warning */
508 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
509 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
510 if (i
== MIGRATION_CAPABILITY_BLOCK
) {
515 head
= g_malloc0(sizeof(*caps
));
518 caps
->next
= g_malloc0(sizeof(*caps
));
522 g_malloc(sizeof(*caps
->value
));
523 caps
->value
->capability
= i
;
524 caps
->value
->state
= s
->enabled_capabilities
[i
];
530 MigrationParameters
*qmp_query_migrate_parameters(Error
**errp
)
532 MigrationParameters
*params
;
533 MigrationState
*s
= migrate_get_current();
535 /* TODO use QAPI_CLONE() instead of duplicating it inline */
536 params
= g_malloc0(sizeof(*params
));
537 params
->has_compress_level
= true;
538 params
->compress_level
= s
->parameters
.compress_level
;
539 params
->has_compress_threads
= true;
540 params
->compress_threads
= s
->parameters
.compress_threads
;
541 params
->has_decompress_threads
= true;
542 params
->decompress_threads
= s
->parameters
.decompress_threads
;
543 params
->has_cpu_throttle_initial
= true;
544 params
->cpu_throttle_initial
= s
->parameters
.cpu_throttle_initial
;
545 params
->has_cpu_throttle_increment
= true;
546 params
->cpu_throttle_increment
= s
->parameters
.cpu_throttle_increment
;
547 params
->has_tls_creds
= true;
548 params
->tls_creds
= g_strdup(s
->parameters
.tls_creds
);
549 params
->has_tls_hostname
= true;
550 params
->tls_hostname
= g_strdup(s
->parameters
.tls_hostname
);
551 params
->has_max_bandwidth
= true;
552 params
->max_bandwidth
= s
->parameters
.max_bandwidth
;
553 params
->has_downtime_limit
= true;
554 params
->downtime_limit
= s
->parameters
.downtime_limit
;
555 params
->has_x_checkpoint_delay
= true;
556 params
->x_checkpoint_delay
= s
->parameters
.x_checkpoint_delay
;
557 params
->has_block_incremental
= true;
558 params
->block_incremental
= s
->parameters
.block_incremental
;
559 params
->has_x_multifd_channels
= true;
560 params
->x_multifd_channels
= s
->parameters
.x_multifd_channels
;
561 params
->has_x_multifd_page_count
= true;
562 params
->x_multifd_page_count
= s
->parameters
.x_multifd_page_count
;
563 params
->has_xbzrle_cache_size
= true;
564 params
->xbzrle_cache_size
= s
->parameters
.xbzrle_cache_size
;
570 * Return true if we're already in the middle of a migration
571 * (i.e. any of the active or setup states)
573 static bool migration_is_setup_or_active(int state
)
576 case MIGRATION_STATUS_ACTIVE
:
577 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
578 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
579 case MIGRATION_STATUS_SETUP
:
580 case MIGRATION_STATUS_PRE_SWITCHOVER
:
581 case MIGRATION_STATUS_DEVICE
:
590 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
592 info
->has_ram
= true;
593 info
->ram
= g_malloc0(sizeof(*info
->ram
));
594 info
->ram
->transferred
= ram_counters
.transferred
;
595 info
->ram
->total
= ram_bytes_total();
596 info
->ram
->duplicate
= ram_counters
.duplicate
;
597 /* legacy value. It is not used anymore */
598 info
->ram
->skipped
= 0;
599 info
->ram
->normal
= ram_counters
.normal
;
600 info
->ram
->normal_bytes
= ram_counters
.normal
*
601 qemu_target_page_size();
602 info
->ram
->mbps
= s
->mbps
;
603 info
->ram
->dirty_sync_count
= ram_counters
.dirty_sync_count
;
604 info
->ram
->postcopy_requests
= ram_counters
.postcopy_requests
;
605 info
->ram
->page_size
= qemu_target_page_size();
607 if (migrate_use_xbzrle()) {
608 info
->has_xbzrle_cache
= true;
609 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
610 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
611 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
612 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
613 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
614 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
615 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
618 if (cpu_throttle_active()) {
619 info
->has_cpu_throttle_percentage
= true;
620 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
623 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
624 info
->ram
->remaining
= ram_bytes_remaining();
625 info
->ram
->dirty_pages_rate
= ram_counters
.dirty_pages_rate
;
629 static void populate_disk_info(MigrationInfo
*info
)
631 if (blk_mig_active()) {
632 info
->has_disk
= true;
633 info
->disk
= g_malloc0(sizeof(*info
->disk
));
634 info
->disk
->transferred
= blk_mig_bytes_transferred();
635 info
->disk
->remaining
= blk_mig_bytes_remaining();
636 info
->disk
->total
= blk_mig_bytes_total();
640 static void fill_source_migration_info(MigrationInfo
*info
)
642 MigrationState
*s
= migrate_get_current();
645 case MIGRATION_STATUS_NONE
:
646 /* no migration has happened ever */
647 /* do not overwrite destination migration status */
650 case MIGRATION_STATUS_SETUP
:
651 info
->has_status
= true;
652 info
->has_total_time
= false;
654 case MIGRATION_STATUS_ACTIVE
:
655 case MIGRATION_STATUS_CANCELLING
:
656 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
657 case MIGRATION_STATUS_PRE_SWITCHOVER
:
658 case MIGRATION_STATUS_DEVICE
:
659 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
660 /* TODO add some postcopy stats */
661 info
->has_status
= true;
662 info
->has_total_time
= true;
663 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
665 info
->has_expected_downtime
= true;
666 info
->expected_downtime
= s
->expected_downtime
;
667 info
->has_setup_time
= true;
668 info
->setup_time
= s
->setup_time
;
670 populate_ram_info(info
, s
);
671 populate_disk_info(info
);
673 case MIGRATION_STATUS_COLO
:
674 info
->has_status
= true;
675 /* TODO: display COLO specific information (checkpoint info etc.) */
677 case MIGRATION_STATUS_COMPLETED
:
678 info
->has_status
= true;
679 info
->has_total_time
= true;
680 info
->total_time
= s
->total_time
;
681 info
->has_downtime
= true;
682 info
->downtime
= s
->downtime
;
683 info
->has_setup_time
= true;
684 info
->setup_time
= s
->setup_time
;
686 populate_ram_info(info
, s
);
688 case MIGRATION_STATUS_FAILED
:
689 info
->has_status
= true;
691 info
->has_error_desc
= true;
692 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
695 case MIGRATION_STATUS_CANCELLED
:
696 info
->has_status
= true;
699 info
->status
= s
->state
;
703 * @migration_caps_check - check capability validity
705 * @cap_list: old capability list, array of bool
706 * @params: new capabilities to be applied soon
707 * @errp: set *errp if the check failed, with reason
709 * Returns true if check passed, otherwise false.
711 static bool migrate_caps_check(bool *cap_list
,
712 MigrationCapabilityStatusList
*params
,
715 MigrationCapabilityStatusList
*cap
;
716 bool old_postcopy_cap
;
717 MigrationIncomingState
*mis
= migration_incoming_get_current();
719 old_postcopy_cap
= cap_list
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
721 for (cap
= params
; cap
; cap
= cap
->next
) {
722 cap_list
[cap
->value
->capability
] = cap
->value
->state
;
725 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
726 if (cap_list
[MIGRATION_CAPABILITY_BLOCK
]) {
727 error_setg(errp
, "QEMU compiled without old-style (blk/-b, inc/-i) "
729 error_append_hint(errp
, "Use drive_mirror+NBD instead.\n");
734 if (cap_list
[MIGRATION_CAPABILITY_POSTCOPY_RAM
]) {
735 if (cap_list
[MIGRATION_CAPABILITY_COMPRESS
]) {
736 /* The decompression threads asynchronously write into RAM
737 * rather than use the atomic copies needed to avoid
738 * userfaulting. It should be possible to fix the decompression
739 * threads for compatibility in future.
741 error_setg(errp
, "Postcopy is not currently compatible "
746 /* This check is reasonably expensive, so only when it's being
747 * set the first time, also it's only the destination that needs
750 if (!old_postcopy_cap
&& runstate_check(RUN_STATE_INMIGRATE
) &&
751 !postcopy_ram_supported_by_host(mis
)) {
752 /* postcopy_ram_supported_by_host will have emitted a more
755 error_setg(errp
, "Postcopy is not supported");
763 static void fill_destination_migration_info(MigrationInfo
*info
)
765 MigrationIncomingState
*mis
= migration_incoming_get_current();
767 switch (mis
->state
) {
768 case MIGRATION_STATUS_NONE
:
771 case MIGRATION_STATUS_SETUP
:
772 case MIGRATION_STATUS_CANCELLING
:
773 case MIGRATION_STATUS_CANCELLED
:
774 case MIGRATION_STATUS_ACTIVE
:
775 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
776 case MIGRATION_STATUS_FAILED
:
777 case MIGRATION_STATUS_COLO
:
778 info
->has_status
= true;
780 case MIGRATION_STATUS_COMPLETED
:
781 info
->has_status
= true;
782 fill_destination_postcopy_migration_info(info
);
785 info
->status
= mis
->state
;
788 MigrationInfo
*qmp_query_migrate(Error
**errp
)
790 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
792 fill_destination_migration_info(info
);
793 fill_source_migration_info(info
);
798 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList
*params
,
801 MigrationState
*s
= migrate_get_current();
802 MigrationCapabilityStatusList
*cap
;
803 bool cap_list
[MIGRATION_CAPABILITY__MAX
];
805 if (migration_is_setup_or_active(s
->state
)) {
806 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
810 memcpy(cap_list
, s
->enabled_capabilities
, sizeof(cap_list
));
811 if (!migrate_caps_check(cap_list
, params
, errp
)) {
815 for (cap
= params
; cap
; cap
= cap
->next
) {
816 s
->enabled_capabilities
[cap
->value
->capability
] = cap
->value
->state
;
821 * Check whether the parameters are valid. Error will be put into errp
822 * (if provided). Return true if valid, otherwise false.
824 static bool migrate_params_check(MigrationParameters
*params
, Error
**errp
)
826 if (params
->has_compress_level
&&
827 (params
->compress_level
> 9)) {
828 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "compress_level",
829 "is invalid, it should be in the range of 0 to 9");
833 if (params
->has_compress_threads
&& (params
->compress_threads
< 1)) {
834 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
836 "is invalid, it should be in the range of 1 to 255");
840 if (params
->has_decompress_threads
&& (params
->decompress_threads
< 1)) {
841 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
842 "decompress_threads",
843 "is invalid, it should be in the range of 1 to 255");
847 if (params
->has_cpu_throttle_initial
&&
848 (params
->cpu_throttle_initial
< 1 ||
849 params
->cpu_throttle_initial
> 99)) {
850 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
851 "cpu_throttle_initial",
852 "an integer in the range of 1 to 99");
856 if (params
->has_cpu_throttle_increment
&&
857 (params
->cpu_throttle_increment
< 1 ||
858 params
->cpu_throttle_increment
> 99)) {
859 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
860 "cpu_throttle_increment",
861 "an integer in the range of 1 to 99");
865 if (params
->has_max_bandwidth
&& (params
->max_bandwidth
> SIZE_MAX
)) {
866 error_setg(errp
, "Parameter 'max_bandwidth' expects an integer in the"
867 " range of 0 to %zu bytes/second", SIZE_MAX
);
871 if (params
->has_downtime_limit
&&
872 (params
->downtime_limit
> MAX_MIGRATE_DOWNTIME
)) {
873 error_setg(errp
, "Parameter 'downtime_limit' expects an integer in "
874 "the range of 0 to %d milliseconds",
875 MAX_MIGRATE_DOWNTIME
);
879 /* x_checkpoint_delay is now always positive */
881 if (params
->has_x_multifd_channels
&& (params
->x_multifd_channels
< 1)) {
882 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
884 "is invalid, it should be in the range of 1 to 255");
887 if (params
->has_x_multifd_page_count
&&
888 (params
->x_multifd_page_count
< 1 ||
889 params
->x_multifd_page_count
> 10000)) {
890 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
891 "multifd_page_count",
892 "is invalid, it should be in the range of 1 to 10000");
896 if (params
->has_xbzrle_cache_size
&&
897 (params
->xbzrle_cache_size
< qemu_target_page_size() ||
898 !is_power_of_2(params
->xbzrle_cache_size
))) {
899 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
901 "is invalid, it should be bigger than target page size"
902 " and a power of two");
909 static void migrate_params_test_apply(MigrateSetParameters
*params
,
910 MigrationParameters
*dest
)
912 *dest
= migrate_get_current()->parameters
;
914 /* TODO use QAPI_CLONE() instead of duplicating it inline */
916 if (params
->has_compress_level
) {
917 dest
->compress_level
= params
->compress_level
;
920 if (params
->has_compress_threads
) {
921 dest
->compress_threads
= params
->compress_threads
;
924 if (params
->has_decompress_threads
) {
925 dest
->decompress_threads
= params
->decompress_threads
;
928 if (params
->has_cpu_throttle_initial
) {
929 dest
->cpu_throttle_initial
= params
->cpu_throttle_initial
;
932 if (params
->has_cpu_throttle_increment
) {
933 dest
->cpu_throttle_increment
= params
->cpu_throttle_increment
;
936 if (params
->has_tls_creds
) {
937 assert(params
->tls_creds
->type
== QTYPE_QSTRING
);
938 dest
->tls_creds
= g_strdup(params
->tls_creds
->u
.s
);
941 if (params
->has_tls_hostname
) {
942 assert(params
->tls_hostname
->type
== QTYPE_QSTRING
);
943 dest
->tls_hostname
= g_strdup(params
->tls_hostname
->u
.s
);
946 if (params
->has_max_bandwidth
) {
947 dest
->max_bandwidth
= params
->max_bandwidth
;
950 if (params
->has_downtime_limit
) {
951 dest
->downtime_limit
= params
->downtime_limit
;
954 if (params
->has_x_checkpoint_delay
) {
955 dest
->x_checkpoint_delay
= params
->x_checkpoint_delay
;
958 if (params
->has_block_incremental
) {
959 dest
->block_incremental
= params
->block_incremental
;
961 if (params
->has_x_multifd_channels
) {
962 dest
->x_multifd_channels
= params
->x_multifd_channels
;
964 if (params
->has_x_multifd_page_count
) {
965 dest
->x_multifd_page_count
= params
->x_multifd_page_count
;
967 if (params
->has_xbzrle_cache_size
) {
968 dest
->xbzrle_cache_size
= params
->xbzrle_cache_size
;
972 static void migrate_params_apply(MigrateSetParameters
*params
, Error
**errp
)
974 MigrationState
*s
= migrate_get_current();
976 /* TODO use QAPI_CLONE() instead of duplicating it inline */
978 if (params
->has_compress_level
) {
979 s
->parameters
.compress_level
= params
->compress_level
;
982 if (params
->has_compress_threads
) {
983 s
->parameters
.compress_threads
= params
->compress_threads
;
986 if (params
->has_decompress_threads
) {
987 s
->parameters
.decompress_threads
= params
->decompress_threads
;
990 if (params
->has_cpu_throttle_initial
) {
991 s
->parameters
.cpu_throttle_initial
= params
->cpu_throttle_initial
;
994 if (params
->has_cpu_throttle_increment
) {
995 s
->parameters
.cpu_throttle_increment
= params
->cpu_throttle_increment
;
998 if (params
->has_tls_creds
) {
999 g_free(s
->parameters
.tls_creds
);
1000 assert(params
->tls_creds
->type
== QTYPE_QSTRING
);
1001 s
->parameters
.tls_creds
= g_strdup(params
->tls_creds
->u
.s
);
1004 if (params
->has_tls_hostname
) {
1005 g_free(s
->parameters
.tls_hostname
);
1006 assert(params
->tls_hostname
->type
== QTYPE_QSTRING
);
1007 s
->parameters
.tls_hostname
= g_strdup(params
->tls_hostname
->u
.s
);
1010 if (params
->has_max_bandwidth
) {
1011 s
->parameters
.max_bandwidth
= params
->max_bandwidth
;
1012 if (s
->to_dst_file
) {
1013 qemu_file_set_rate_limit(s
->to_dst_file
,
1014 s
->parameters
.max_bandwidth
/ XFER_LIMIT_RATIO
);
1018 if (params
->has_downtime_limit
) {
1019 s
->parameters
.downtime_limit
= params
->downtime_limit
;
1022 if (params
->has_x_checkpoint_delay
) {
1023 s
->parameters
.x_checkpoint_delay
= params
->x_checkpoint_delay
;
1024 if (migration_in_colo_state()) {
1025 colo_checkpoint_notify(s
);
1029 if (params
->has_block_incremental
) {
1030 s
->parameters
.block_incremental
= params
->block_incremental
;
1032 if (params
->has_x_multifd_channels
) {
1033 s
->parameters
.x_multifd_channels
= params
->x_multifd_channels
;
1035 if (params
->has_x_multifd_page_count
) {
1036 s
->parameters
.x_multifd_page_count
= params
->x_multifd_page_count
;
1038 if (params
->has_xbzrle_cache_size
) {
1039 s
->parameters
.xbzrle_cache_size
= params
->xbzrle_cache_size
;
1040 xbzrle_cache_resize(params
->xbzrle_cache_size
, errp
);
1044 void qmp_migrate_set_parameters(MigrateSetParameters
*params
, Error
**errp
)
1046 MigrationParameters tmp
;
1048 /* TODO Rewrite "" to null instead */
1049 if (params
->has_tls_creds
1050 && params
->tls_creds
->type
== QTYPE_QNULL
) {
1051 qobject_unref(params
->tls_creds
->u
.n
);
1052 params
->tls_creds
->type
= QTYPE_QSTRING
;
1053 params
->tls_creds
->u
.s
= strdup("");
1055 /* TODO Rewrite "" to null instead */
1056 if (params
->has_tls_hostname
1057 && params
->tls_hostname
->type
== QTYPE_QNULL
) {
1058 qobject_unref(params
->tls_hostname
->u
.n
);
1059 params
->tls_hostname
->type
= QTYPE_QSTRING
;
1060 params
->tls_hostname
->u
.s
= strdup("");
1063 migrate_params_test_apply(params
, &tmp
);
1065 if (!migrate_params_check(&tmp
, errp
)) {
1066 /* Invalid parameter */
1070 migrate_params_apply(params
, errp
);
1074 void qmp_migrate_start_postcopy(Error
**errp
)
1076 MigrationState
*s
= migrate_get_current();
1078 if (!migrate_postcopy()) {
1079 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1080 " the start of migration");
1084 if (s
->state
== MIGRATION_STATUS_NONE
) {
1085 error_setg(errp
, "Postcopy must be started after migration has been"
1090 * we don't error if migration has finished since that would be racy
1091 * with issuing this command.
1093 atomic_set(&s
->start_postcopy
, true);
1096 /* shared migration helpers */
1098 void migrate_set_state(int *state
, int old_state
, int new_state
)
1100 assert(new_state
< MIGRATION_STATUS__MAX
);
1101 if (atomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1102 trace_migrate_set_state(MigrationStatus_str(new_state
));
1103 migrate_generate_event(new_state
);
1107 static MigrationCapabilityStatusList
*migrate_cap_add(
1108 MigrationCapabilityStatusList
*list
,
1109 MigrationCapability index
,
1112 MigrationCapabilityStatusList
*cap
;
1114 cap
= g_new0(MigrationCapabilityStatusList
, 1);
1115 cap
->value
= g_new0(MigrationCapabilityStatus
, 1);
1116 cap
->value
->capability
= index
;
1117 cap
->value
->state
= state
;
1123 void migrate_set_block_enabled(bool value
, Error
**errp
)
1125 MigrationCapabilityStatusList
*cap
;
1127 cap
= migrate_cap_add(NULL
, MIGRATION_CAPABILITY_BLOCK
, value
);
1128 qmp_migrate_set_capabilities(cap
, errp
);
1129 qapi_free_MigrationCapabilityStatusList(cap
);
1132 static void migrate_set_block_incremental(MigrationState
*s
, bool value
)
1134 s
->parameters
.block_incremental
= value
;
1137 static void block_cleanup_parameters(MigrationState
*s
)
1139 if (s
->must_remove_block_options
) {
1140 /* setting to false can never fail */
1141 migrate_set_block_enabled(false, &error_abort
);
1142 migrate_set_block_incremental(s
, false);
1143 s
->must_remove_block_options
= false;
1147 static void migrate_fd_cleanup(void *opaque
)
1149 MigrationState
*s
= opaque
;
1151 qemu_bh_delete(s
->cleanup_bh
);
1152 s
->cleanup_bh
= NULL
;
1154 qemu_savevm_state_cleanup();
1156 if (s
->to_dst_file
) {
1157 Error
*local_err
= NULL
;
1159 trace_migrate_fd_cleanup();
1160 qemu_mutex_unlock_iothread();
1161 if (s
->migration_thread_running
) {
1162 qemu_thread_join(&s
->thread
);
1163 s
->migration_thread_running
= false;
1165 qemu_mutex_lock_iothread();
1167 if (multifd_save_cleanup(&local_err
) != 0) {
1168 error_report_err(local_err
);
1170 qemu_fclose(s
->to_dst_file
);
1171 s
->to_dst_file
= NULL
;
1174 assert((s
->state
!= MIGRATION_STATUS_ACTIVE
) &&
1175 (s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
));
1177 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1178 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1179 MIGRATION_STATUS_CANCELLED
);
1183 /* It is used on info migrate. We can't free it */
1184 error_report_err(error_copy(s
->error
));
1186 notifier_list_notify(&migration_state_notifiers
, s
);
1187 block_cleanup_parameters(s
);
1190 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1192 qemu_mutex_lock(&s
->error_mutex
);
1194 s
->error
= error_copy(error
);
1196 qemu_mutex_unlock(&s
->error_mutex
);
1199 void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1201 trace_migrate_fd_error(error_get_pretty(error
));
1202 assert(s
->to_dst_file
== NULL
);
1203 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1204 MIGRATION_STATUS_FAILED
);
1205 migrate_set_error(s
, error
);
1208 static void migrate_fd_cancel(MigrationState
*s
)
1211 QEMUFile
*f
= migrate_get_current()->to_dst_file
;
1212 trace_migrate_fd_cancel();
1214 if (s
->rp_state
.from_dst_file
) {
1215 /* shutdown the rp socket, so causing the rp thread to shutdown */
1216 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1220 old_state
= s
->state
;
1221 if (!migration_is_setup_or_active(old_state
)) {
1224 /* If the migration is paused, kick it out of the pause */
1225 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1226 qemu_sem_post(&s
->pause_sem
);
1228 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1229 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1232 * If we're unlucky the migration code might be stuck somewhere in a
1233 * send/write while the network has failed and is waiting to timeout;
1234 * if we've got shutdown(2) available then we can force it to quit.
1235 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1236 * called in a bh, so there is no race against this cancel.
1238 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
1239 qemu_file_shutdown(f
);
1241 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1242 Error
*local_err
= NULL
;
1244 bdrv_invalidate_cache_all(&local_err
);
1246 error_report_err(local_err
);
1248 s
->block_inactive
= false;
1253 void add_migration_state_change_notifier(Notifier
*notify
)
1255 notifier_list_add(&migration_state_notifiers
, notify
);
1258 void remove_migration_state_change_notifier(Notifier
*notify
)
1260 notifier_remove(notify
);
1263 bool migration_in_setup(MigrationState
*s
)
1265 return s
->state
== MIGRATION_STATUS_SETUP
;
1268 bool migration_has_finished(MigrationState
*s
)
1270 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1273 bool migration_has_failed(MigrationState
*s
)
1275 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1276 s
->state
== MIGRATION_STATUS_FAILED
);
1279 bool migration_in_postcopy(void)
1281 MigrationState
*s
= migrate_get_current();
1283 return (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1286 bool migration_in_postcopy_after_devices(MigrationState
*s
)
1288 return migration_in_postcopy() && s
->postcopy_after_devices
;
1291 bool migration_is_idle(void)
1293 MigrationState
*s
= migrate_get_current();
1296 case MIGRATION_STATUS_NONE
:
1297 case MIGRATION_STATUS_CANCELLED
:
1298 case MIGRATION_STATUS_COMPLETED
:
1299 case MIGRATION_STATUS_FAILED
:
1301 case MIGRATION_STATUS_SETUP
:
1302 case MIGRATION_STATUS_CANCELLING
:
1303 case MIGRATION_STATUS_ACTIVE
:
1304 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1305 case MIGRATION_STATUS_COLO
:
1306 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1307 case MIGRATION_STATUS_DEVICE
:
1309 case MIGRATION_STATUS__MAX
:
1310 g_assert_not_reached();
1316 void migrate_init(MigrationState
*s
)
1319 * Reinitialise all migration state, except
1320 * parameters/capabilities that the user set, and
1326 s
->to_dst_file
= NULL
;
1327 s
->state
= MIGRATION_STATUS_NONE
;
1328 s
->rp_state
.from_dst_file
= NULL
;
1329 s
->rp_state
.error
= false;
1332 s
->expected_downtime
= 0;
1334 s
->start_postcopy
= false;
1335 s
->postcopy_after_devices
= false;
1336 s
->migration_thread_running
= false;
1337 error_free(s
->error
);
1340 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1342 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1344 s
->vm_was_running
= false;
1345 s
->iteration_initial_bytes
= 0;
1346 s
->threshold_size
= 0;
1349 static GSList
*migration_blockers
;
1351 int migrate_add_blocker(Error
*reason
, Error
**errp
)
1353 if (migrate_get_current()->only_migratable
) {
1354 error_propagate(errp
, error_copy(reason
));
1355 error_prepend(errp
, "disallowing migration blocker "
1356 "(--only_migratable) for: ");
1360 if (migration_is_idle()) {
1361 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
1365 error_propagate(errp
, error_copy(reason
));
1366 error_prepend(errp
, "disallowing migration blocker (migration in "
1371 void migrate_del_blocker(Error
*reason
)
1373 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
1376 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
1378 Error
*local_err
= NULL
;
1379 static bool once
= true;
1381 if (!deferred_incoming
) {
1382 error_setg(errp
, "For use with '-incoming defer'");
1386 error_setg(errp
, "The incoming migration has already been started");
1389 qemu_start_incoming_migration(uri
, &local_err
);
1392 error_propagate(errp
, local_err
);
1399 bool migration_is_blocked(Error
**errp
)
1401 if (qemu_savevm_state_blocked(errp
)) {
1405 if (migration_blockers
) {
1406 error_propagate(errp
, error_copy(migration_blockers
->data
));
1413 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1414 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1417 Error
*local_err
= NULL
;
1418 MigrationState
*s
= migrate_get_current();
1421 if (migration_is_setup_or_active(s
->state
) ||
1422 s
->state
== MIGRATION_STATUS_CANCELLING
||
1423 s
->state
== MIGRATION_STATUS_COLO
) {
1424 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1427 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1428 error_setg(errp
, "Guest is waiting for an incoming migration");
1432 if (migration_is_blocked(errp
)) {
1436 if ((has_blk
&& blk
) || (has_inc
&& inc
)) {
1437 if (migrate_use_block() || migrate_use_block_incremental()) {
1438 error_setg(errp
, "Command options are incompatible with "
1439 "current migration capabilities");
1442 migrate_set_block_enabled(true, &local_err
);
1444 error_propagate(errp
, local_err
);
1447 s
->must_remove_block_options
= true;
1450 if (has_inc
&& inc
) {
1451 migrate_set_block_incremental(s
, true);
1456 if (strstart(uri
, "tcp:", &p
)) {
1457 tcp_start_outgoing_migration(s
, p
, &local_err
);
1459 } else if (strstart(uri
, "rdma:", &p
)) {
1460 rdma_start_outgoing_migration(s
, p
, &local_err
);
1462 } else if (strstart(uri
, "exec:", &p
)) {
1463 exec_start_outgoing_migration(s
, p
, &local_err
);
1464 } else if (strstart(uri
, "unix:", &p
)) {
1465 unix_start_outgoing_migration(s
, p
, &local_err
);
1466 } else if (strstart(uri
, "fd:", &p
)) {
1467 fd_start_outgoing_migration(s
, p
, &local_err
);
1469 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1470 "a valid migration protocol");
1471 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1472 MIGRATION_STATUS_FAILED
);
1473 block_cleanup_parameters(s
);
1478 migrate_fd_error(s
, local_err
);
1479 error_propagate(errp
, local_err
);
1484 void qmp_migrate_cancel(Error
**errp
)
1486 migrate_fd_cancel(migrate_get_current());
1489 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
1491 MigrationState
*s
= migrate_get_current();
1492 if (s
->state
!= state
) {
1493 error_setg(errp
, "Migration not in expected state: %s",
1494 MigrationStatus_str(s
->state
));
1497 qemu_sem_post(&s
->pause_sem
);
1500 void qmp_migrate_set_cache_size(int64_t value
, Error
**errp
)
1502 MigrateSetParameters p
= {
1503 .has_xbzrle_cache_size
= true,
1504 .xbzrle_cache_size
= value
,
1507 qmp_migrate_set_parameters(&p
, errp
);
1510 int64_t qmp_query_migrate_cache_size(Error
**errp
)
1512 return migrate_xbzrle_cache_size();
1515 void qmp_migrate_set_speed(int64_t value
, Error
**errp
)
1517 MigrateSetParameters p
= {
1518 .has_max_bandwidth
= true,
1519 .max_bandwidth
= value
,
1522 qmp_migrate_set_parameters(&p
, errp
);
1525 void qmp_migrate_set_downtime(double value
, Error
**errp
)
1527 if (value
< 0 || value
> MAX_MIGRATE_DOWNTIME_SECONDS
) {
1528 error_setg(errp
, "Parameter 'downtime_limit' expects an integer in "
1529 "the range of 0 to %d seconds",
1530 MAX_MIGRATE_DOWNTIME_SECONDS
);
1534 value
*= 1000; /* Convert to milliseconds */
1535 value
= MAX(0, MIN(INT64_MAX
, value
));
1537 MigrateSetParameters p
= {
1538 .has_downtime_limit
= true,
1539 .downtime_limit
= value
,
1542 qmp_migrate_set_parameters(&p
, errp
);
1545 bool migrate_release_ram(void)
1549 s
= migrate_get_current();
1551 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_RELEASE_RAM
];
1554 bool migrate_postcopy_ram(void)
1558 s
= migrate_get_current();
1560 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
1563 bool migrate_postcopy(void)
1565 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1568 bool migrate_auto_converge(void)
1572 s
= migrate_get_current();
1574 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_AUTO_CONVERGE
];
1577 bool migrate_zero_blocks(void)
1581 s
= migrate_get_current();
1583 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_ZERO_BLOCKS
];
1586 bool migrate_postcopy_blocktime(void)
1590 s
= migrate_get_current();
1592 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME
];
1595 bool migrate_use_compression(void)
1599 s
= migrate_get_current();
1601 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_COMPRESS
];
1604 int migrate_compress_level(void)
1608 s
= migrate_get_current();
1610 return s
->parameters
.compress_level
;
1613 int migrate_compress_threads(void)
1617 s
= migrate_get_current();
1619 return s
->parameters
.compress_threads
;
1622 int migrate_decompress_threads(void)
1626 s
= migrate_get_current();
1628 return s
->parameters
.decompress_threads
;
1631 bool migrate_dirty_bitmaps(void)
1635 s
= migrate_get_current();
1637 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_DIRTY_BITMAPS
];
1640 bool migrate_use_events(void)
1644 s
= migrate_get_current();
1646 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_EVENTS
];
1649 bool migrate_use_multifd(void)
1653 s
= migrate_get_current();
1655 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_X_MULTIFD
];
1658 bool migrate_pause_before_switchover(void)
1662 s
= migrate_get_current();
1664 return s
->enabled_capabilities
[
1665 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER
];
1668 int migrate_multifd_channels(void)
1672 s
= migrate_get_current();
1674 return s
->parameters
.x_multifd_channels
;
1677 int migrate_multifd_page_count(void)
1681 s
= migrate_get_current();
1683 return s
->parameters
.x_multifd_page_count
;
1686 int migrate_use_xbzrle(void)
1690 s
= migrate_get_current();
1692 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_XBZRLE
];
1695 int64_t migrate_xbzrle_cache_size(void)
1699 s
= migrate_get_current();
1701 return s
->parameters
.xbzrle_cache_size
;
1704 bool migrate_use_block(void)
1708 s
= migrate_get_current();
1710 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_BLOCK
];
1713 bool migrate_use_return_path(void)
1717 s
= migrate_get_current();
1719 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_RETURN_PATH
];
1722 bool migrate_use_block_incremental(void)
1726 s
= migrate_get_current();
1728 return s
->parameters
.block_incremental
;
1731 /* migration thread support */
1733 * Something bad happened to the RP stream, mark an error
1734 * The caller shall print or trace something to indicate why
1736 static void mark_source_rp_bad(MigrationState
*s
)
1738 s
->rp_state
.error
= true;
1741 static struct rp_cmd_args
{
1742 ssize_t len
; /* -1 = variable */
1745 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1746 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1747 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1748 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1749 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1750 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1754 * Process a request for pages received on the return path,
1755 * We're allowed to send more than requested (e.g. to round to our page size)
1756 * and we don't need to send pages that have already been sent.
1758 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1759 ram_addr_t start
, size_t len
)
1761 long our_host_ps
= getpagesize();
1763 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1766 * Since we currently insist on matching page sizes, just sanity check
1767 * we're being asked for whole host pages.
1769 if (start
& (our_host_ps
-1) ||
1770 (len
& (our_host_ps
-1))) {
1771 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1772 " len: %zd", __func__
, start
, len
);
1773 mark_source_rp_bad(ms
);
1777 if (ram_save_queue_pages(rbname
, start
, len
)) {
1778 mark_source_rp_bad(ms
);
1783 * Handles messages sent on the return path towards the source VM
1786 static void *source_return_path_thread(void *opaque
)
1788 MigrationState
*ms
= opaque
;
1789 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1790 uint16_t header_len
, header_type
;
1792 uint32_t tmp32
, sibling_error
;
1793 ram_addr_t start
= 0; /* =0 to silence warning */
1794 size_t len
= 0, expected_len
;
1797 trace_source_return_path_thread_entry();
1798 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1799 migration_is_setup_or_active(ms
->state
)) {
1800 trace_source_return_path_thread_loop_top();
1801 header_type
= qemu_get_be16(rp
);
1802 header_len
= qemu_get_be16(rp
);
1804 if (qemu_file_get_error(rp
)) {
1805 mark_source_rp_bad(ms
);
1809 if (header_type
>= MIG_RP_MSG_MAX
||
1810 header_type
== MIG_RP_MSG_INVALID
) {
1811 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1812 header_type
, header_len
);
1813 mark_source_rp_bad(ms
);
1817 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1818 header_len
!= rp_cmd_args
[header_type
].len
) ||
1819 header_len
> sizeof(buf
)) {
1820 error_report("RP: Received '%s' message (0x%04x) with"
1821 "incorrect length %d expecting %zu",
1822 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1823 (size_t)rp_cmd_args
[header_type
].len
);
1824 mark_source_rp_bad(ms
);
1828 /* We know we've got a valid header by this point */
1829 res
= qemu_get_buffer(rp
, buf
, header_len
);
1830 if (res
!= header_len
) {
1831 error_report("RP: Failed reading data for message 0x%04x"
1832 " read %d expected %d",
1833 header_type
, res
, header_len
);
1834 mark_source_rp_bad(ms
);
1838 /* OK, we have the message and the data */
1839 switch (header_type
) {
1840 case MIG_RP_MSG_SHUT
:
1841 sibling_error
= ldl_be_p(buf
);
1842 trace_source_return_path_thread_shut(sibling_error
);
1843 if (sibling_error
) {
1844 error_report("RP: Sibling indicated error %d", sibling_error
);
1845 mark_source_rp_bad(ms
);
1848 * We'll let the main thread deal with closing the RP
1849 * we could do a shutdown(2) on it, but we're the only user
1850 * anyway, so there's nothing gained.
1854 case MIG_RP_MSG_PONG
:
1855 tmp32
= ldl_be_p(buf
);
1856 trace_source_return_path_thread_pong(tmp32
);
1859 case MIG_RP_MSG_REQ_PAGES
:
1860 start
= ldq_be_p(buf
);
1861 len
= ldl_be_p(buf
+ 8);
1862 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1865 case MIG_RP_MSG_REQ_PAGES_ID
:
1866 expected_len
= 12 + 1; /* header + termination */
1868 if (header_len
>= expected_len
) {
1869 start
= ldq_be_p(buf
);
1870 len
= ldl_be_p(buf
+ 8);
1871 /* Now we expect an idstr */
1872 tmp32
= buf
[12]; /* Length of the following idstr */
1873 buf
[13 + tmp32
] = '\0';
1874 expected_len
+= tmp32
;
1876 if (header_len
!= expected_len
) {
1877 error_report("RP: Req_Page_id with length %d expecting %zd",
1878 header_len
, expected_len
);
1879 mark_source_rp_bad(ms
);
1882 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1889 if (qemu_file_get_error(rp
)) {
1890 trace_source_return_path_thread_bad_end();
1891 mark_source_rp_bad(ms
);
1894 trace_source_return_path_thread_end();
1896 ms
->rp_state
.from_dst_file
= NULL
;
1901 static int open_return_path_on_source(MigrationState
*ms
)
1904 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
1905 if (!ms
->rp_state
.from_dst_file
) {
1909 trace_open_return_path_on_source();
1910 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
1911 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
1913 trace_open_return_path_on_source_continue();
1918 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1919 static int await_return_path_close_on_source(MigrationState
*ms
)
1922 * If this is a normal exit then the destination will send a SHUT and the
1923 * rp_thread will exit, however if there's an error we need to cause
1926 if (qemu_file_get_error(ms
->to_dst_file
) && ms
->rp_state
.from_dst_file
) {
1928 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1929 * waiting for the destination.
1931 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
1932 mark_source_rp_bad(ms
);
1934 trace_await_return_path_close_on_source_joining();
1935 qemu_thread_join(&ms
->rp_state
.rp_thread
);
1936 trace_await_return_path_close_on_source_close();
1937 return ms
->rp_state
.error
;
1941 * Switch from normal iteration to postcopy
1942 * Returns non-0 on error
1944 static int postcopy_start(MigrationState
*ms
)
1947 QIOChannelBuffer
*bioc
;
1949 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1950 bool restart_block
= false;
1951 int cur_state
= MIGRATION_STATUS_ACTIVE
;
1952 if (!migrate_pause_before_switchover()) {
1953 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
1954 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1957 trace_postcopy_start();
1958 qemu_mutex_lock_iothread();
1959 trace_postcopy_start_set_run();
1961 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1962 global_state_store();
1963 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1968 ret
= migration_maybe_pause(ms
, &cur_state
,
1969 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1974 ret
= bdrv_inactivate_all();
1978 restart_block
= true;
1981 * Cause any non-postcopiable, but iterative devices to
1982 * send out their final data.
1984 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
1987 * in Finish migrate and with the io-lock held everything should
1988 * be quiet, but we've potentially still got dirty pages and we
1989 * need to tell the destination to throw any pages it's already received
1992 if (migrate_postcopy_ram()) {
1993 if (ram_postcopy_send_discard_bitmap(ms
)) {
1994 error_report("postcopy send discard bitmap failed");
2000 * send rest of state - note things that are doing postcopy
2001 * will notice we're in POSTCOPY_ACTIVE and not actually
2002 * wrap their state up here
2004 qemu_file_set_rate_limit(ms
->to_dst_file
, INT64_MAX
);
2005 if (migrate_postcopy_ram()) {
2006 /* Ping just for debugging, helps line traces up */
2007 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2011 * While loading the device state we may trigger page transfer
2012 * requests and the fd must be free to process those, and thus
2013 * the destination must read the whole device state off the fd before
2014 * it starts processing it. Unfortunately the ad-hoc migration format
2015 * doesn't allow the destination to know the size to read without fully
2016 * parsing it through each devices load-state code (especially the open
2017 * coded devices that use get/put).
2018 * So we wrap the device state up in a package with a length at the start;
2019 * to do this we use a qemu_buf to hold the whole of the device state.
2021 bioc
= qio_channel_buffer_new(4096);
2022 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2023 fb
= qemu_fopen_channel_output(QIO_CHANNEL(bioc
));
2024 object_unref(OBJECT(bioc
));
2027 * Make sure the receiver can get incoming pages before we send the rest
2030 qemu_savevm_send_postcopy_listen(fb
);
2032 qemu_savevm_state_complete_precopy(fb
, false, false);
2033 if (migrate_postcopy_ram()) {
2034 qemu_savevm_send_ping(fb
, 3);
2037 qemu_savevm_send_postcopy_run(fb
);
2039 /* <><> end of stuff going into the package */
2041 /* Last point of recovery; as soon as we send the package the destination
2042 * can open devices and potentially start running.
2043 * Lets just check again we've not got any errors.
2045 ret
= qemu_file_get_error(ms
->to_dst_file
);
2047 error_report("postcopy_start: Migration stream errored (pre package)");
2051 restart_block
= false;
2053 /* Now send that blob */
2054 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2059 /* Send a notify to give a chance for anything that needs to happen
2060 * at the transition to postcopy and after the device state; in particular
2061 * spice needs to trigger a transition now
2063 ms
->postcopy_after_devices
= true;
2064 notifier_list_notify(&migration_state_notifiers
, ms
);
2066 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
2068 qemu_mutex_unlock_iothread();
2070 if (migrate_postcopy_ram()) {
2072 * Although this ping is just for debug, it could potentially be
2073 * used for getting a better measurement of downtime at the source.
2075 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2078 if (migrate_release_ram()) {
2079 ram_postcopy_migrated_memory_release(ms
);
2082 ret
= qemu_file_get_error(ms
->to_dst_file
);
2084 error_report("postcopy_start: Migration stream errored");
2085 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2086 MIGRATION_STATUS_FAILED
);
2094 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2095 MIGRATION_STATUS_FAILED
);
2096 if (restart_block
) {
2097 /* A failure happened early enough that we know the destination hasn't
2098 * accessed block devices, so we're safe to recover.
2100 Error
*local_err
= NULL
;
2102 bdrv_invalidate_cache_all(&local_err
);
2104 error_report_err(local_err
);
2107 qemu_mutex_unlock_iothread();
2112 * migration_maybe_pause: Pause if required to by
2113 * migrate_pause_before_switchover called with the iothread locked
2114 * Returns: 0 on success
2116 static int migration_maybe_pause(MigrationState
*s
,
2117 int *current_active_state
,
2120 if (!migrate_pause_before_switchover()) {
2124 /* Since leaving this state is not atomic with posting the semaphore
2125 * it's possible that someone could have issued multiple migrate_continue
2126 * and the semaphore is incorrectly positive at this point;
2127 * the docs say it's undefined to reinit a semaphore that's already
2128 * init'd, so use timedwait to eat up any existing posts.
2130 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2131 /* This block intentionally left blank */
2134 qemu_mutex_unlock_iothread();
2135 migrate_set_state(&s
->state
, *current_active_state
,
2136 MIGRATION_STATUS_PRE_SWITCHOVER
);
2137 qemu_sem_wait(&s
->pause_sem
);
2138 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2140 *current_active_state
= new_state
;
2141 qemu_mutex_lock_iothread();
2143 return s
->state
== new_state
? 0 : -EINVAL
;
2147 * migration_completion: Used by migration_thread when there's not much left.
2148 * The caller 'breaks' the loop when this returns.
2150 * @s: Current migration state
2152 static void migration_completion(MigrationState
*s
)
2155 int current_active_state
= s
->state
;
2157 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2158 qemu_mutex_lock_iothread();
2159 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2160 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
2161 s
->vm_was_running
= runstate_is_running();
2162 ret
= global_state_store();
2165 bool inactivate
= !migrate_colo_enabled();
2166 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2168 ret
= migration_maybe_pause(s
, ¤t_active_state
,
2169 MIGRATION_STATUS_DEVICE
);
2172 qemu_file_set_rate_limit(s
->to_dst_file
, INT64_MAX
);
2173 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2176 if (inactivate
&& ret
>= 0) {
2177 s
->block_inactive
= true;
2180 qemu_mutex_unlock_iothread();
2185 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2186 trace_migration_completion_postcopy_end();
2188 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2189 trace_migration_completion_postcopy_end_after_complete();
2193 * If rp was opened we must clean up the thread before
2194 * cleaning everything else up (since if there are no failures
2195 * it will wait for the destination to send it's status in
2198 if (s
->rp_state
.from_dst_file
) {
2200 trace_migration_return_path_end_before();
2201 rp_error
= await_return_path_close_on_source(s
);
2202 trace_migration_return_path_end_after(rp_error
);
2204 goto fail_invalidate
;
2208 if (qemu_file_get_error(s
->to_dst_file
)) {
2209 trace_migration_completion_file_err();
2210 goto fail_invalidate
;
2213 if (!migrate_colo_enabled()) {
2214 migrate_set_state(&s
->state
, current_active_state
,
2215 MIGRATION_STATUS_COMPLETED
);
2221 /* If not doing postcopy, vm_start() will be called: let's regain
2222 * control on images.
2224 if (s
->state
== MIGRATION_STATUS_ACTIVE
||
2225 s
->state
== MIGRATION_STATUS_DEVICE
) {
2226 Error
*local_err
= NULL
;
2228 qemu_mutex_lock_iothread();
2229 bdrv_invalidate_cache_all(&local_err
);
2231 error_report_err(local_err
);
2233 s
->block_inactive
= false;
2235 qemu_mutex_unlock_iothread();
2239 migrate_set_state(&s
->state
, current_active_state
,
2240 MIGRATION_STATUS_FAILED
);
2243 bool migrate_colo_enabled(void)
2245 MigrationState
*s
= migrate_get_current();
2246 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_X_COLO
];
2249 typedef enum MigThrError
{
2250 /* No error detected */
2251 MIG_THR_ERR_NONE
= 0,
2252 /* Detected error, but resumed successfully */
2253 MIG_THR_ERR_RECOVERED
= 1,
2254 /* Detected fatal error, need to exit */
2255 MIG_THR_ERR_FATAL
= 2,
2259 * We don't return until we are in a safe state to continue current
2260 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2261 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2263 static MigThrError
postcopy_pause(MigrationState
*s
)
2265 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2266 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2267 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2269 /* Current channel is possibly broken. Release it. */
2270 assert(s
->to_dst_file
);
2271 qemu_file_shutdown(s
->to_dst_file
);
2272 qemu_fclose(s
->to_dst_file
);
2273 s
->to_dst_file
= NULL
;
2275 error_report("Detected IO failure for postcopy. "
2276 "Migration paused.");
2279 * We wait until things fixed up. Then someone will setup the
2280 * status back for us.
2282 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2283 qemu_sem_wait(&s
->postcopy_pause_sem
);
2286 trace_postcopy_pause_continued();
2288 return MIG_THR_ERR_RECOVERED
;
2291 static MigThrError
migration_detect_error(MigrationState
*s
)
2295 /* Try to detect any file errors */
2296 ret
= qemu_file_get_error(s
->to_dst_file
);
2299 /* Everything is fine */
2300 return MIG_THR_ERR_NONE
;
2303 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
== -EIO
) {
2305 * For postcopy, we allow the network to be down for a
2306 * while. After that, it can be continued by a
2309 return postcopy_pause(s
);
2312 * For precopy (or postcopy with error outside IO), we fail
2315 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
2316 trace_migration_thread_file_err();
2318 /* Time to stop the migration, now. */
2319 return MIG_THR_ERR_FATAL
;
2323 static void migration_calculate_complete(MigrationState
*s
)
2325 uint64_t bytes
= qemu_ftell(s
->to_dst_file
);
2326 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2328 s
->total_time
= end_time
- s
->start_time
;
2331 * It's still not set, so we are precopy migration. For
2332 * postcopy, downtime is calculated during postcopy_start().
2334 s
->downtime
= end_time
- s
->downtime_start
;
2337 if (s
->total_time
) {
2338 s
->mbps
= ((double) bytes
* 8.0) / s
->total_time
/ 1000;
2342 static void migration_update_counters(MigrationState
*s
,
2343 int64_t current_time
)
2345 uint64_t transferred
, time_spent
;
2348 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
2352 transferred
= qemu_ftell(s
->to_dst_file
) - s
->iteration_initial_bytes
;
2353 time_spent
= current_time
- s
->iteration_start_time
;
2354 bandwidth
= (double)transferred
/ time_spent
;
2355 s
->threshold_size
= bandwidth
* s
->parameters
.downtime_limit
;
2357 s
->mbps
= (((double) transferred
* 8.0) /
2358 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
2361 * if we haven't sent anything, we don't want to
2362 * recalculate. 10000 is a small enough number for our purposes
2364 if (ram_counters
.dirty_pages_rate
&& transferred
> 10000) {
2365 s
->expected_downtime
= ram_counters
.dirty_pages_rate
*
2366 qemu_target_page_size() / bandwidth
;
2369 qemu_file_reset_rate_limit(s
->to_dst_file
);
2371 s
->iteration_start_time
= current_time
;
2372 s
->iteration_initial_bytes
= qemu_ftell(s
->to_dst_file
);
2374 trace_migrate_transferred(transferred
, time_spent
,
2375 bandwidth
, s
->threshold_size
);
2378 /* Migration thread iteration status */
2380 MIG_ITERATE_RESUME
, /* Resume current iteration */
2381 MIG_ITERATE_SKIP
, /* Skip current iteration */
2382 MIG_ITERATE_BREAK
, /* Break the loop */
2386 * Return true if continue to the next iteration directly, false
2389 static MigIterateState
migration_iteration_run(MigrationState
*s
)
2391 uint64_t pending_size
, pend_pre
, pend_compat
, pend_post
;
2392 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
2394 qemu_savevm_state_pending(s
->to_dst_file
, s
->threshold_size
, &pend_pre
,
2395 &pend_compat
, &pend_post
);
2396 pending_size
= pend_pre
+ pend_compat
+ pend_post
;
2398 trace_migrate_pending(pending_size
, s
->threshold_size
,
2399 pend_pre
, pend_compat
, pend_post
);
2401 if (pending_size
&& pending_size
>= s
->threshold_size
) {
2402 /* Still a significant amount to transfer */
2403 if (migrate_postcopy() && !in_postcopy
&&
2404 pend_pre
<= s
->threshold_size
&&
2405 atomic_read(&s
->start_postcopy
)) {
2406 if (postcopy_start(s
)) {
2407 error_report("%s: postcopy failed to start", __func__
);
2409 return MIG_ITERATE_SKIP
;
2411 /* Just another iteration step */
2412 qemu_savevm_state_iterate(s
->to_dst_file
,
2413 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2415 trace_migration_thread_low_pending(pending_size
);
2416 migration_completion(s
);
2417 return MIG_ITERATE_BREAK
;
2420 return MIG_ITERATE_RESUME
;
2423 static void migration_iteration_finish(MigrationState
*s
)
2425 /* If we enabled cpu throttling for auto-converge, turn it off. */
2426 cpu_throttle_stop();
2428 qemu_mutex_lock_iothread();
2430 case MIGRATION_STATUS_COMPLETED
:
2431 migration_calculate_complete(s
);
2432 runstate_set(RUN_STATE_POSTMIGRATE
);
2435 case MIGRATION_STATUS_ACTIVE
:
2437 * We should really assert here, but since it's during
2438 * migration, let's try to reduce the usage of assertions.
2440 if (!migrate_colo_enabled()) {
2441 error_report("%s: critical error: calling COLO code without "
2442 "COLO enabled", __func__
);
2444 migrate_start_colo_process(s
);
2446 * Fixme: we will run VM in COLO no matter its old running state.
2447 * After exited COLO, we will keep running.
2449 s
->vm_was_running
= true;
2451 case MIGRATION_STATUS_FAILED
:
2452 case MIGRATION_STATUS_CANCELLED
:
2453 if (s
->vm_was_running
) {
2456 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
2457 runstate_set(RUN_STATE_POSTMIGRATE
);
2463 /* Should not reach here, but if so, forgive the VM. */
2464 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
2467 qemu_bh_schedule(s
->cleanup_bh
);
2468 qemu_mutex_unlock_iothread();
2472 * Master migration thread on the source VM.
2473 * It drives the migration and pumps the data down the outgoing channel.
2475 static void *migration_thread(void *opaque
)
2477 MigrationState
*s
= opaque
;
2478 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
2479 MigThrError thr_error
;
2481 rcu_register_thread();
2483 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2485 qemu_savevm_state_header(s
->to_dst_file
);
2488 * If we opened the return path, we need to make sure dst has it
2491 if (s
->rp_state
.from_dst_file
) {
2492 /* Now tell the dest that it should open its end so it can reply */
2493 qemu_savevm_send_open_return_path(s
->to_dst_file
);
2495 /* And do a ping that will make stuff easier to debug */
2496 qemu_savevm_send_ping(s
->to_dst_file
, 1);
2499 if (migrate_postcopy()) {
2501 * Tell the destination that we *might* want to do postcopy later;
2502 * if the other end can't do postcopy it should fail now, nice and
2505 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
2508 qemu_savevm_state_setup(s
->to_dst_file
);
2510 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
2511 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
2512 MIGRATION_STATUS_ACTIVE
);
2514 trace_migration_thread_setup_complete();
2516 while (s
->state
== MIGRATION_STATUS_ACTIVE
||
2517 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2518 int64_t current_time
;
2520 if (!qemu_file_rate_limit(s
->to_dst_file
)) {
2521 MigIterateState iter_state
= migration_iteration_run(s
);
2522 if (iter_state
== MIG_ITERATE_SKIP
) {
2524 } else if (iter_state
== MIG_ITERATE_BREAK
) {
2530 * Try to detect any kind of failures, and see whether we
2531 * should stop the migration now.
2533 thr_error
= migration_detect_error(s
);
2534 if (thr_error
== MIG_THR_ERR_FATAL
) {
2535 /* Stop migration */
2537 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
2539 * Just recovered from a e.g. network failure, reset all
2540 * the local variables. This is important to avoid
2541 * breaking transferred_bytes and bandwidth calculation
2543 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2544 s
->iteration_initial_bytes
= 0;
2547 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2549 migration_update_counters(s
, current_time
);
2551 if (qemu_file_rate_limit(s
->to_dst_file
)) {
2552 /* usleep expects microseconds */
2553 g_usleep((s
->iteration_start_time
+ BUFFER_DELAY
-
2554 current_time
) * 1000);
2558 trace_migration_thread_after_loop();
2559 migration_iteration_finish(s
);
2560 rcu_unregister_thread();
2564 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
2566 s
->expected_downtime
= s
->parameters
.downtime_limit
;
2567 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
2569 migrate_fd_error(s
, error_in
);
2570 migrate_fd_cleanup(s
);
2574 qemu_file_set_blocking(s
->to_dst_file
, true);
2575 qemu_file_set_rate_limit(s
->to_dst_file
,
2576 s
->parameters
.max_bandwidth
/ XFER_LIMIT_RATIO
);
2578 /* Notify before starting migration thread */
2579 notifier_list_notify(&migration_state_notifiers
, s
);
2582 * Open the return path. For postcopy, it is used exclusively. For
2583 * precopy, only if user specified "return-path" capability would
2584 * QEMU uses the return path.
2586 if (migrate_postcopy_ram() || migrate_use_return_path()) {
2587 if (open_return_path_on_source(s
)) {
2588 error_report("Unable to open return-path for postcopy");
2589 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
2590 MIGRATION_STATUS_FAILED
);
2591 migrate_fd_cleanup(s
);
2596 if (multifd_save_setup() != 0) {
2597 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
2598 MIGRATION_STATUS_FAILED
);
2599 migrate_fd_cleanup(s
);
2602 qemu_thread_create(&s
->thread
, "live_migration", migration_thread
, s
,
2603 QEMU_THREAD_JOINABLE
);
2604 s
->migration_thread_running
= true;
2607 void migration_global_dump(Monitor
*mon
)
2609 MigrationState
*ms
= migrate_get_current();
2611 monitor_printf(mon
, "globals:\n");
2612 monitor_printf(mon
, "store-global-state: %s\n",
2613 ms
->store_global_state
? "on" : "off");
2614 monitor_printf(mon
, "only-migratable: %s\n",
2615 ms
->only_migratable
? "on" : "off");
2616 monitor_printf(mon
, "send-configuration: %s\n",
2617 ms
->send_configuration
? "on" : "off");
2618 monitor_printf(mon
, "send-section-footer: %s\n",
2619 ms
->send_section_footer
? "on" : "off");
2622 #define DEFINE_PROP_MIG_CAP(name, x) \
2623 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2625 static Property migration_properties
[] = {
2626 DEFINE_PROP_BOOL("store-global-state", MigrationState
,
2627 store_global_state
, true),
2628 DEFINE_PROP_BOOL("only-migratable", MigrationState
, only_migratable
, false),
2629 DEFINE_PROP_BOOL("send-configuration", MigrationState
,
2630 send_configuration
, true),
2631 DEFINE_PROP_BOOL("send-section-footer", MigrationState
,
2632 send_section_footer
, true),
2634 /* Migration parameters */
2635 DEFINE_PROP_UINT8("x-compress-level", MigrationState
,
2636 parameters
.compress_level
,
2637 DEFAULT_MIGRATE_COMPRESS_LEVEL
),
2638 DEFINE_PROP_UINT8("x-compress-threads", MigrationState
,
2639 parameters
.compress_threads
,
2640 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT
),
2641 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState
,
2642 parameters
.decompress_threads
,
2643 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT
),
2644 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState
,
2645 parameters
.cpu_throttle_initial
,
2646 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL
),
2647 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState
,
2648 parameters
.cpu_throttle_increment
,
2649 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT
),
2650 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState
,
2651 parameters
.max_bandwidth
, MAX_THROTTLE
),
2652 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState
,
2653 parameters
.downtime_limit
,
2654 DEFAULT_MIGRATE_SET_DOWNTIME
),
2655 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState
,
2656 parameters
.x_checkpoint_delay
,
2657 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY
),
2658 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState
,
2659 parameters
.x_multifd_channels
,
2660 DEFAULT_MIGRATE_MULTIFD_CHANNELS
),
2661 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState
,
2662 parameters
.x_multifd_page_count
,
2663 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT
),
2664 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState
,
2665 parameters
.xbzrle_cache_size
,
2666 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE
),
2668 /* Migration capabilities */
2669 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE
),
2670 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL
),
2671 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE
),
2672 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS
),
2673 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS
),
2674 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS
),
2675 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM
),
2676 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO
),
2677 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM
),
2678 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK
),
2679 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH
),
2680 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD
),
2682 DEFINE_PROP_END_OF_LIST(),
2685 static void migration_class_init(ObjectClass
*klass
, void *data
)
2687 DeviceClass
*dc
= DEVICE_CLASS(klass
);
2689 dc
->user_creatable
= false;
2690 dc
->props
= migration_properties
;
2693 static void migration_instance_finalize(Object
*obj
)
2695 MigrationState
*ms
= MIGRATION_OBJ(obj
);
2696 MigrationParameters
*params
= &ms
->parameters
;
2698 qemu_mutex_destroy(&ms
->error_mutex
);
2699 g_free(params
->tls_hostname
);
2700 g_free(params
->tls_creds
);
2701 qemu_sem_destroy(&ms
->pause_sem
);
2702 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
2703 error_free(ms
->error
);
2706 static void migration_instance_init(Object
*obj
)
2708 MigrationState
*ms
= MIGRATION_OBJ(obj
);
2709 MigrationParameters
*params
= &ms
->parameters
;
2711 ms
->state
= MIGRATION_STATUS_NONE
;
2713 qemu_sem_init(&ms
->pause_sem
, 0);
2714 qemu_mutex_init(&ms
->error_mutex
);
2716 params
->tls_hostname
= g_strdup("");
2717 params
->tls_creds
= g_strdup("");
2719 /* Set has_* up only for parameter checks */
2720 params
->has_compress_level
= true;
2721 params
->has_compress_threads
= true;
2722 params
->has_decompress_threads
= true;
2723 params
->has_cpu_throttle_initial
= true;
2724 params
->has_cpu_throttle_increment
= true;
2725 params
->has_max_bandwidth
= true;
2726 params
->has_downtime_limit
= true;
2727 params
->has_x_checkpoint_delay
= true;
2728 params
->has_block_incremental
= true;
2729 params
->has_x_multifd_channels
= true;
2730 params
->has_x_multifd_page_count
= true;
2731 params
->has_xbzrle_cache_size
= true;
2733 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
2737 * Return true if check pass, false otherwise. Error will be put
2738 * inside errp if provided.
2740 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
2742 MigrationCapabilityStatusList
*head
= NULL
;
2743 /* Assuming all off */
2744 bool cap_list
[MIGRATION_CAPABILITY__MAX
] = { 0 }, ret
;
2747 if (!migrate_params_check(&ms
->parameters
, errp
)) {
2751 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
2752 if (ms
->enabled_capabilities
[i
]) {
2753 head
= migrate_cap_add(head
, i
, true);
2757 ret
= migrate_caps_check(cap_list
, head
, errp
);
2759 /* It works with head == NULL */
2760 qapi_free_MigrationCapabilityStatusList(head
);
2765 static const TypeInfo migration_type
= {
2766 .name
= TYPE_MIGRATION
,
2768 * NOTE: TYPE_MIGRATION is not really a device, as the object is
2769 * not created using qdev_create(), it is not attached to the qdev
2770 * device tree, and it is never realized.
2772 * TODO: Make this TYPE_OBJECT once QOM provides something like
2773 * TYPE_DEVICE's "-global" properties.
2775 .parent
= TYPE_DEVICE
,
2776 .class_init
= migration_class_init
,
2777 .class_size
= sizeof(MigrationClass
),
2778 .instance_size
= sizeof(MigrationState
),
2779 .instance_init
= migration_instance_init
,
2780 .instance_finalize
= migration_instance_finalize
,
2783 static void register_migration_types(void)
2785 type_register_static(&migration_type
);
2788 type_init(register_migration_types
);