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);
163 qemu_sem_init(&mis_current
.postcopy_pause_sem_fault
, 0);
165 init_dirty_bitmap_incoming_migration();
172 void migration_incoming_state_destroy(void)
174 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
176 if (mis
->to_src_file
) {
177 /* Tell source that we are done */
178 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
179 qemu_fclose(mis
->to_src_file
);
180 mis
->to_src_file
= NULL
;
183 if (mis
->from_src_file
) {
184 qemu_fclose(mis
->from_src_file
);
185 mis
->from_src_file
= NULL
;
187 if (mis
->postcopy_remote_fds
) {
188 g_array_free(mis
->postcopy_remote_fds
, TRUE
);
189 mis
->postcopy_remote_fds
= NULL
;
192 qemu_event_reset(&mis
->main_thread_load_event
);
195 static void migrate_generate_event(int new_state
)
197 if (migrate_use_events()) {
198 qapi_event_send_migration(new_state
, &error_abort
);
203 * Called on -incoming with a defer: uri.
204 * The migration can be started later after any parameters have been
207 static void deferred_incoming_migration(Error
**errp
)
209 if (deferred_incoming
) {
210 error_setg(errp
, "Incoming migration already deferred");
212 deferred_incoming
= true;
216 * Send a message on the return channel back to the source
219 static int migrate_send_rp_message(MigrationIncomingState
*mis
,
220 enum mig_rp_message_type message_type
,
221 uint16_t len
, void *data
)
225 trace_migrate_send_rp_message((int)message_type
, len
);
226 qemu_mutex_lock(&mis
->rp_mutex
);
229 * It's possible that the file handle got lost due to network
232 if (!mis
->to_src_file
) {
237 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
238 qemu_put_be16(mis
->to_src_file
, len
);
239 qemu_put_buffer(mis
->to_src_file
, data
, len
);
240 qemu_fflush(mis
->to_src_file
);
242 /* It's possible that qemu file got error during sending */
243 ret
= qemu_file_get_error(mis
->to_src_file
);
246 qemu_mutex_unlock(&mis
->rp_mutex
);
250 /* Request a range of pages from the source VM at the given
252 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
253 * as the last request (a name must have been given previously)
254 * Start: Address offset within the RB
255 * Len: Length in bytes required - must be a multiple of pagesize
257 int migrate_send_rp_req_pages(MigrationIncomingState
*mis
, const char *rbname
,
258 ram_addr_t start
, size_t len
)
260 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
261 size_t msglen
= 12; /* start + len */
262 enum mig_rp_message_type msg_type
;
264 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
265 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
268 int rbname_len
= strlen(rbname
);
269 assert(rbname_len
< 256);
271 bufc
[msglen
++] = rbname_len
;
272 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
273 msglen
+= rbname_len
;
274 msg_type
= MIG_RP_MSG_REQ_PAGES_ID
;
276 msg_type
= MIG_RP_MSG_REQ_PAGES
;
279 return migrate_send_rp_message(mis
, msg_type
, msglen
, bufc
);
282 void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
286 qapi_event_send_migration(MIGRATION_STATUS_SETUP
, &error_abort
);
287 if (!strcmp(uri
, "defer")) {
288 deferred_incoming_migration(errp
);
289 } else if (strstart(uri
, "tcp:", &p
)) {
290 tcp_start_incoming_migration(p
, errp
);
292 } else if (strstart(uri
, "rdma:", &p
)) {
293 rdma_start_incoming_migration(p
, errp
);
295 } else if (strstart(uri
, "exec:", &p
)) {
296 exec_start_incoming_migration(p
, errp
);
297 } else if (strstart(uri
, "unix:", &p
)) {
298 unix_start_incoming_migration(p
, errp
);
299 } else if (strstart(uri
, "fd:", &p
)) {
300 fd_start_incoming_migration(p
, errp
);
302 error_setg(errp
, "unknown migration protocol: %s", uri
);
306 static void process_incoming_migration_bh(void *opaque
)
308 Error
*local_err
= NULL
;
309 MigrationIncomingState
*mis
= opaque
;
311 /* Make sure all file formats flush their mutable metadata.
312 * If we get an error here, just don't restart the VM yet. */
313 bdrv_invalidate_cache_all(&local_err
);
315 error_report_err(local_err
);
321 * This must happen after all error conditions are dealt with and
322 * we're sure the VM is going to be running on this host.
324 qemu_announce_self();
326 if (multifd_load_cleanup(&local_err
) != 0) {
327 error_report_err(local_err
);
330 /* If global state section was not received or we are in running
331 state, we need to obey autostart. Any other state is set with
334 dirty_bitmap_mig_before_vm_start();
336 if (!global_state_received() ||
337 global_state_get_runstate() == RUN_STATE_RUNNING
) {
341 runstate_set(RUN_STATE_PAUSED
);
344 runstate_set(global_state_get_runstate());
347 * This must happen after any state changes since as soon as an external
348 * observer sees this event they might start to prod at the VM assuming
351 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
352 MIGRATION_STATUS_COMPLETED
);
353 qemu_bh_delete(mis
->bh
);
354 migration_incoming_state_destroy();
357 static void process_incoming_migration_co(void *opaque
)
359 MigrationIncomingState
*mis
= migration_incoming_get_current();
363 assert(mis
->from_src_file
);
364 mis
->largest_page_size
= qemu_ram_pagesize_largest();
365 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
366 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
367 MIGRATION_STATUS_ACTIVE
);
368 ret
= qemu_loadvm_state(mis
->from_src_file
);
370 ps
= postcopy_state_get();
371 trace_process_incoming_migration_co_end(ret
, ps
);
372 if (ps
!= POSTCOPY_INCOMING_NONE
) {
373 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
375 * Where a migration had postcopy enabled (and thus went to advise)
376 * but managed to complete within the precopy period, we can use
379 postcopy_ram_incoming_cleanup(mis
);
380 } else if (ret
>= 0) {
382 * Postcopy was started, cleanup should happen at the end of the
385 trace_process_incoming_migration_co_postcopy_end_main();
388 /* Else if something went wrong then just fall out of the normal exit */
391 /* we get COLO info, and know if we are in COLO mode */
392 if (!ret
&& migration_incoming_enable_colo()) {
393 mis
->migration_incoming_co
= qemu_coroutine_self();
394 qemu_thread_create(&mis
->colo_incoming_thread
, "COLO incoming",
395 colo_process_incoming_thread
, mis
, QEMU_THREAD_JOINABLE
);
396 mis
->have_colo_incoming_thread
= true;
397 qemu_coroutine_yield();
399 /* Wait checkpoint incoming thread exit before free resource */
400 qemu_thread_join(&mis
->colo_incoming_thread
);
404 Error
*local_err
= NULL
;
406 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
407 MIGRATION_STATUS_FAILED
);
408 error_report("load of migration failed: %s", strerror(-ret
));
409 qemu_fclose(mis
->from_src_file
);
410 if (multifd_load_cleanup(&local_err
) != 0) {
411 error_report_err(local_err
);
415 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
416 qemu_bh_schedule(mis
->bh
);
419 static void migration_incoming_setup(QEMUFile
*f
)
421 MigrationIncomingState
*mis
= migration_incoming_get_current();
423 if (multifd_load_setup() != 0) {
424 /* We haven't been able to create multifd threads
425 nothing better to do */
429 if (!mis
->from_src_file
) {
430 mis
->from_src_file
= f
;
432 qemu_file_set_blocking(f
, false);
435 void migration_incoming_process(void)
437 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
438 qemu_coroutine_enter(co
);
441 void migration_fd_process_incoming(QEMUFile
*f
)
443 MigrationIncomingState
*mis
= migration_incoming_get_current();
445 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
446 /* Resumed from a paused postcopy migration */
448 mis
->from_src_file
= f
;
449 /* Postcopy has standalone thread to do vm load */
450 qemu_file_set_blocking(f
, true);
452 /* Re-configure the return path */
453 mis
->to_src_file
= qemu_file_get_return_path(f
);
455 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
456 MIGRATION_STATUS_POSTCOPY_RECOVER
);
459 * Here, we only wake up the main loading thread (while the
460 * fault thread will still be waiting), so that we can receive
461 * commands from source now, and answer it if needed. The
462 * fault thread will be woken up afterwards until we are sure
463 * that source is ready to reply to page requests.
465 qemu_sem_post(&mis
->postcopy_pause_sem_dst
);
467 /* New incoming migration */
468 migration_incoming_setup(f
);
469 migration_incoming_process();
473 void migration_ioc_process_incoming(QIOChannel
*ioc
)
475 MigrationIncomingState
*mis
= migration_incoming_get_current();
477 if (!mis
->from_src_file
) {
478 QEMUFile
*f
= qemu_fopen_channel_input(ioc
);
479 migration_incoming_setup(f
);
482 multifd_recv_new_channel(ioc
);
486 * @migration_has_all_channels: We have received all channels that we need
488 * Returns true when we have got connections to all the channels that
489 * we need for migration.
491 bool migration_has_all_channels(void)
495 all_channels
= multifd_recv_all_channels_created();
501 * Send a 'SHUT' message on the return channel with the given value
502 * to indicate that we've finished with the RP. Non-0 value indicates
505 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
510 buf
= cpu_to_be32(value
);
511 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
515 * Send a 'PONG' message on the return channel with the given value
516 * (normally in response to a 'PING')
518 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
523 buf
= cpu_to_be32(value
);
524 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
527 MigrationCapabilityStatusList
*qmp_query_migrate_capabilities(Error
**errp
)
529 MigrationCapabilityStatusList
*head
= NULL
;
530 MigrationCapabilityStatusList
*caps
;
531 MigrationState
*s
= migrate_get_current();
534 caps
= NULL
; /* silence compiler warning */
535 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
536 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
537 if (i
== MIGRATION_CAPABILITY_BLOCK
) {
542 head
= g_malloc0(sizeof(*caps
));
545 caps
->next
= g_malloc0(sizeof(*caps
));
549 g_malloc(sizeof(*caps
->value
));
550 caps
->value
->capability
= i
;
551 caps
->value
->state
= s
->enabled_capabilities
[i
];
557 MigrationParameters
*qmp_query_migrate_parameters(Error
**errp
)
559 MigrationParameters
*params
;
560 MigrationState
*s
= migrate_get_current();
562 /* TODO use QAPI_CLONE() instead of duplicating it inline */
563 params
= g_malloc0(sizeof(*params
));
564 params
->has_compress_level
= true;
565 params
->compress_level
= s
->parameters
.compress_level
;
566 params
->has_compress_threads
= true;
567 params
->compress_threads
= s
->parameters
.compress_threads
;
568 params
->has_decompress_threads
= true;
569 params
->decompress_threads
= s
->parameters
.decompress_threads
;
570 params
->has_cpu_throttle_initial
= true;
571 params
->cpu_throttle_initial
= s
->parameters
.cpu_throttle_initial
;
572 params
->has_cpu_throttle_increment
= true;
573 params
->cpu_throttle_increment
= s
->parameters
.cpu_throttle_increment
;
574 params
->has_tls_creds
= true;
575 params
->tls_creds
= g_strdup(s
->parameters
.tls_creds
);
576 params
->has_tls_hostname
= true;
577 params
->tls_hostname
= g_strdup(s
->parameters
.tls_hostname
);
578 params
->has_max_bandwidth
= true;
579 params
->max_bandwidth
= s
->parameters
.max_bandwidth
;
580 params
->has_downtime_limit
= true;
581 params
->downtime_limit
= s
->parameters
.downtime_limit
;
582 params
->has_x_checkpoint_delay
= true;
583 params
->x_checkpoint_delay
= s
->parameters
.x_checkpoint_delay
;
584 params
->has_block_incremental
= true;
585 params
->block_incremental
= s
->parameters
.block_incremental
;
586 params
->has_x_multifd_channels
= true;
587 params
->x_multifd_channels
= s
->parameters
.x_multifd_channels
;
588 params
->has_x_multifd_page_count
= true;
589 params
->x_multifd_page_count
= s
->parameters
.x_multifd_page_count
;
590 params
->has_xbzrle_cache_size
= true;
591 params
->xbzrle_cache_size
= s
->parameters
.xbzrle_cache_size
;
597 * Return true if we're already in the middle of a migration
598 * (i.e. any of the active or setup states)
600 static bool migration_is_setup_or_active(int state
)
603 case MIGRATION_STATUS_ACTIVE
:
604 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
605 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
606 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
607 case MIGRATION_STATUS_SETUP
:
608 case MIGRATION_STATUS_PRE_SWITCHOVER
:
609 case MIGRATION_STATUS_DEVICE
:
618 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
620 info
->has_ram
= true;
621 info
->ram
= g_malloc0(sizeof(*info
->ram
));
622 info
->ram
->transferred
= ram_counters
.transferred
;
623 info
->ram
->total
= ram_bytes_total();
624 info
->ram
->duplicate
= ram_counters
.duplicate
;
625 /* legacy value. It is not used anymore */
626 info
->ram
->skipped
= 0;
627 info
->ram
->normal
= ram_counters
.normal
;
628 info
->ram
->normal_bytes
= ram_counters
.normal
*
629 qemu_target_page_size();
630 info
->ram
->mbps
= s
->mbps
;
631 info
->ram
->dirty_sync_count
= ram_counters
.dirty_sync_count
;
632 info
->ram
->postcopy_requests
= ram_counters
.postcopy_requests
;
633 info
->ram
->page_size
= qemu_target_page_size();
635 if (migrate_use_xbzrle()) {
636 info
->has_xbzrle_cache
= true;
637 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
638 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
639 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
640 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
641 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
642 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
643 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
646 if (cpu_throttle_active()) {
647 info
->has_cpu_throttle_percentage
= true;
648 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
651 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
652 info
->ram
->remaining
= ram_bytes_remaining();
653 info
->ram
->dirty_pages_rate
= ram_counters
.dirty_pages_rate
;
657 static void populate_disk_info(MigrationInfo
*info
)
659 if (blk_mig_active()) {
660 info
->has_disk
= true;
661 info
->disk
= g_malloc0(sizeof(*info
->disk
));
662 info
->disk
->transferred
= blk_mig_bytes_transferred();
663 info
->disk
->remaining
= blk_mig_bytes_remaining();
664 info
->disk
->total
= blk_mig_bytes_total();
668 static void fill_source_migration_info(MigrationInfo
*info
)
670 MigrationState
*s
= migrate_get_current();
673 case MIGRATION_STATUS_NONE
:
674 /* no migration has happened ever */
675 /* do not overwrite destination migration status */
678 case MIGRATION_STATUS_SETUP
:
679 info
->has_status
= true;
680 info
->has_total_time
= false;
682 case MIGRATION_STATUS_ACTIVE
:
683 case MIGRATION_STATUS_CANCELLING
:
684 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
685 case MIGRATION_STATUS_PRE_SWITCHOVER
:
686 case MIGRATION_STATUS_DEVICE
:
687 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
688 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
689 /* TODO add some postcopy stats */
690 info
->has_status
= true;
691 info
->has_total_time
= true;
692 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
694 info
->has_expected_downtime
= true;
695 info
->expected_downtime
= s
->expected_downtime
;
696 info
->has_setup_time
= true;
697 info
->setup_time
= s
->setup_time
;
699 populate_ram_info(info
, s
);
700 populate_disk_info(info
);
702 case MIGRATION_STATUS_COLO
:
703 info
->has_status
= true;
704 /* TODO: display COLO specific information (checkpoint info etc.) */
706 case MIGRATION_STATUS_COMPLETED
:
707 info
->has_status
= true;
708 info
->has_total_time
= true;
709 info
->total_time
= s
->total_time
;
710 info
->has_downtime
= true;
711 info
->downtime
= s
->downtime
;
712 info
->has_setup_time
= true;
713 info
->setup_time
= s
->setup_time
;
715 populate_ram_info(info
, s
);
717 case MIGRATION_STATUS_FAILED
:
718 info
->has_status
= true;
720 info
->has_error_desc
= true;
721 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
724 case MIGRATION_STATUS_CANCELLED
:
725 info
->has_status
= true;
728 info
->status
= s
->state
;
732 * @migration_caps_check - check capability validity
734 * @cap_list: old capability list, array of bool
735 * @params: new capabilities to be applied soon
736 * @errp: set *errp if the check failed, with reason
738 * Returns true if check passed, otherwise false.
740 static bool migrate_caps_check(bool *cap_list
,
741 MigrationCapabilityStatusList
*params
,
744 MigrationCapabilityStatusList
*cap
;
745 bool old_postcopy_cap
;
746 MigrationIncomingState
*mis
= migration_incoming_get_current();
748 old_postcopy_cap
= cap_list
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
750 for (cap
= params
; cap
; cap
= cap
->next
) {
751 cap_list
[cap
->value
->capability
] = cap
->value
->state
;
754 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
755 if (cap_list
[MIGRATION_CAPABILITY_BLOCK
]) {
756 error_setg(errp
, "QEMU compiled without old-style (blk/-b, inc/-i) "
758 error_append_hint(errp
, "Use drive_mirror+NBD instead.\n");
763 if (cap_list
[MIGRATION_CAPABILITY_POSTCOPY_RAM
]) {
764 if (cap_list
[MIGRATION_CAPABILITY_COMPRESS
]) {
765 /* The decompression threads asynchronously write into RAM
766 * rather than use the atomic copies needed to avoid
767 * userfaulting. It should be possible to fix the decompression
768 * threads for compatibility in future.
770 error_setg(errp
, "Postcopy is not currently compatible "
775 /* This check is reasonably expensive, so only when it's being
776 * set the first time, also it's only the destination that needs
779 if (!old_postcopy_cap
&& runstate_check(RUN_STATE_INMIGRATE
) &&
780 !postcopy_ram_supported_by_host(mis
)) {
781 /* postcopy_ram_supported_by_host will have emitted a more
784 error_setg(errp
, "Postcopy is not supported");
792 static void fill_destination_migration_info(MigrationInfo
*info
)
794 MigrationIncomingState
*mis
= migration_incoming_get_current();
796 switch (mis
->state
) {
797 case MIGRATION_STATUS_NONE
:
800 case MIGRATION_STATUS_SETUP
:
801 case MIGRATION_STATUS_CANCELLING
:
802 case MIGRATION_STATUS_CANCELLED
:
803 case MIGRATION_STATUS_ACTIVE
:
804 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
805 case MIGRATION_STATUS_FAILED
:
806 case MIGRATION_STATUS_COLO
:
807 info
->has_status
= true;
809 case MIGRATION_STATUS_COMPLETED
:
810 info
->has_status
= true;
811 fill_destination_postcopy_migration_info(info
);
814 info
->status
= mis
->state
;
817 MigrationInfo
*qmp_query_migrate(Error
**errp
)
819 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
821 fill_destination_migration_info(info
);
822 fill_source_migration_info(info
);
827 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList
*params
,
830 MigrationState
*s
= migrate_get_current();
831 MigrationCapabilityStatusList
*cap
;
832 bool cap_list
[MIGRATION_CAPABILITY__MAX
];
834 if (migration_is_setup_or_active(s
->state
)) {
835 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
839 memcpy(cap_list
, s
->enabled_capabilities
, sizeof(cap_list
));
840 if (!migrate_caps_check(cap_list
, params
, errp
)) {
844 for (cap
= params
; cap
; cap
= cap
->next
) {
845 s
->enabled_capabilities
[cap
->value
->capability
] = cap
->value
->state
;
850 * Check whether the parameters are valid. Error will be put into errp
851 * (if provided). Return true if valid, otherwise false.
853 static bool migrate_params_check(MigrationParameters
*params
, Error
**errp
)
855 if (params
->has_compress_level
&&
856 (params
->compress_level
> 9)) {
857 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "compress_level",
858 "is invalid, it should be in the range of 0 to 9");
862 if (params
->has_compress_threads
&& (params
->compress_threads
< 1)) {
863 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
865 "is invalid, it should be in the range of 1 to 255");
869 if (params
->has_decompress_threads
&& (params
->decompress_threads
< 1)) {
870 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
871 "decompress_threads",
872 "is invalid, it should be in the range of 1 to 255");
876 if (params
->has_cpu_throttle_initial
&&
877 (params
->cpu_throttle_initial
< 1 ||
878 params
->cpu_throttle_initial
> 99)) {
879 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
880 "cpu_throttle_initial",
881 "an integer in the range of 1 to 99");
885 if (params
->has_cpu_throttle_increment
&&
886 (params
->cpu_throttle_increment
< 1 ||
887 params
->cpu_throttle_increment
> 99)) {
888 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
889 "cpu_throttle_increment",
890 "an integer in the range of 1 to 99");
894 if (params
->has_max_bandwidth
&& (params
->max_bandwidth
> SIZE_MAX
)) {
895 error_setg(errp
, "Parameter 'max_bandwidth' expects an integer in the"
896 " range of 0 to %zu bytes/second", SIZE_MAX
);
900 if (params
->has_downtime_limit
&&
901 (params
->downtime_limit
> MAX_MIGRATE_DOWNTIME
)) {
902 error_setg(errp
, "Parameter 'downtime_limit' expects an integer in "
903 "the range of 0 to %d milliseconds",
904 MAX_MIGRATE_DOWNTIME
);
908 /* x_checkpoint_delay is now always positive */
910 if (params
->has_x_multifd_channels
&& (params
->x_multifd_channels
< 1)) {
911 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
913 "is invalid, it should be in the range of 1 to 255");
916 if (params
->has_x_multifd_page_count
&&
917 (params
->x_multifd_page_count
< 1 ||
918 params
->x_multifd_page_count
> 10000)) {
919 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
920 "multifd_page_count",
921 "is invalid, it should be in the range of 1 to 10000");
925 if (params
->has_xbzrle_cache_size
&&
926 (params
->xbzrle_cache_size
< qemu_target_page_size() ||
927 !is_power_of_2(params
->xbzrle_cache_size
))) {
928 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
930 "is invalid, it should be bigger than target page size"
931 " and a power of two");
938 static void migrate_params_test_apply(MigrateSetParameters
*params
,
939 MigrationParameters
*dest
)
941 *dest
= migrate_get_current()->parameters
;
943 /* TODO use QAPI_CLONE() instead of duplicating it inline */
945 if (params
->has_compress_level
) {
946 dest
->compress_level
= params
->compress_level
;
949 if (params
->has_compress_threads
) {
950 dest
->compress_threads
= params
->compress_threads
;
953 if (params
->has_decompress_threads
) {
954 dest
->decompress_threads
= params
->decompress_threads
;
957 if (params
->has_cpu_throttle_initial
) {
958 dest
->cpu_throttle_initial
= params
->cpu_throttle_initial
;
961 if (params
->has_cpu_throttle_increment
) {
962 dest
->cpu_throttle_increment
= params
->cpu_throttle_increment
;
965 if (params
->has_tls_creds
) {
966 assert(params
->tls_creds
->type
== QTYPE_QSTRING
);
967 dest
->tls_creds
= g_strdup(params
->tls_creds
->u
.s
);
970 if (params
->has_tls_hostname
) {
971 assert(params
->tls_hostname
->type
== QTYPE_QSTRING
);
972 dest
->tls_hostname
= g_strdup(params
->tls_hostname
->u
.s
);
975 if (params
->has_max_bandwidth
) {
976 dest
->max_bandwidth
= params
->max_bandwidth
;
979 if (params
->has_downtime_limit
) {
980 dest
->downtime_limit
= params
->downtime_limit
;
983 if (params
->has_x_checkpoint_delay
) {
984 dest
->x_checkpoint_delay
= params
->x_checkpoint_delay
;
987 if (params
->has_block_incremental
) {
988 dest
->block_incremental
= params
->block_incremental
;
990 if (params
->has_x_multifd_channels
) {
991 dest
->x_multifd_channels
= params
->x_multifd_channels
;
993 if (params
->has_x_multifd_page_count
) {
994 dest
->x_multifd_page_count
= params
->x_multifd_page_count
;
996 if (params
->has_xbzrle_cache_size
) {
997 dest
->xbzrle_cache_size
= params
->xbzrle_cache_size
;
1001 static void migrate_params_apply(MigrateSetParameters
*params
, Error
**errp
)
1003 MigrationState
*s
= migrate_get_current();
1005 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1007 if (params
->has_compress_level
) {
1008 s
->parameters
.compress_level
= params
->compress_level
;
1011 if (params
->has_compress_threads
) {
1012 s
->parameters
.compress_threads
= params
->compress_threads
;
1015 if (params
->has_decompress_threads
) {
1016 s
->parameters
.decompress_threads
= params
->decompress_threads
;
1019 if (params
->has_cpu_throttle_initial
) {
1020 s
->parameters
.cpu_throttle_initial
= params
->cpu_throttle_initial
;
1023 if (params
->has_cpu_throttle_increment
) {
1024 s
->parameters
.cpu_throttle_increment
= params
->cpu_throttle_increment
;
1027 if (params
->has_tls_creds
) {
1028 g_free(s
->parameters
.tls_creds
);
1029 assert(params
->tls_creds
->type
== QTYPE_QSTRING
);
1030 s
->parameters
.tls_creds
= g_strdup(params
->tls_creds
->u
.s
);
1033 if (params
->has_tls_hostname
) {
1034 g_free(s
->parameters
.tls_hostname
);
1035 assert(params
->tls_hostname
->type
== QTYPE_QSTRING
);
1036 s
->parameters
.tls_hostname
= g_strdup(params
->tls_hostname
->u
.s
);
1039 if (params
->has_max_bandwidth
) {
1040 s
->parameters
.max_bandwidth
= params
->max_bandwidth
;
1041 if (s
->to_dst_file
) {
1042 qemu_file_set_rate_limit(s
->to_dst_file
,
1043 s
->parameters
.max_bandwidth
/ XFER_LIMIT_RATIO
);
1047 if (params
->has_downtime_limit
) {
1048 s
->parameters
.downtime_limit
= params
->downtime_limit
;
1051 if (params
->has_x_checkpoint_delay
) {
1052 s
->parameters
.x_checkpoint_delay
= params
->x_checkpoint_delay
;
1053 if (migration_in_colo_state()) {
1054 colo_checkpoint_notify(s
);
1058 if (params
->has_block_incremental
) {
1059 s
->parameters
.block_incremental
= params
->block_incremental
;
1061 if (params
->has_x_multifd_channels
) {
1062 s
->parameters
.x_multifd_channels
= params
->x_multifd_channels
;
1064 if (params
->has_x_multifd_page_count
) {
1065 s
->parameters
.x_multifd_page_count
= params
->x_multifd_page_count
;
1067 if (params
->has_xbzrle_cache_size
) {
1068 s
->parameters
.xbzrle_cache_size
= params
->xbzrle_cache_size
;
1069 xbzrle_cache_resize(params
->xbzrle_cache_size
, errp
);
1073 void qmp_migrate_set_parameters(MigrateSetParameters
*params
, Error
**errp
)
1075 MigrationParameters tmp
;
1077 /* TODO Rewrite "" to null instead */
1078 if (params
->has_tls_creds
1079 && params
->tls_creds
->type
== QTYPE_QNULL
) {
1080 qobject_unref(params
->tls_creds
->u
.n
);
1081 params
->tls_creds
->type
= QTYPE_QSTRING
;
1082 params
->tls_creds
->u
.s
= strdup("");
1084 /* TODO Rewrite "" to null instead */
1085 if (params
->has_tls_hostname
1086 && params
->tls_hostname
->type
== QTYPE_QNULL
) {
1087 qobject_unref(params
->tls_hostname
->u
.n
);
1088 params
->tls_hostname
->type
= QTYPE_QSTRING
;
1089 params
->tls_hostname
->u
.s
= strdup("");
1092 migrate_params_test_apply(params
, &tmp
);
1094 if (!migrate_params_check(&tmp
, errp
)) {
1095 /* Invalid parameter */
1099 migrate_params_apply(params
, errp
);
1103 void qmp_migrate_start_postcopy(Error
**errp
)
1105 MigrationState
*s
= migrate_get_current();
1107 if (!migrate_postcopy()) {
1108 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1109 " the start of migration");
1113 if (s
->state
== MIGRATION_STATUS_NONE
) {
1114 error_setg(errp
, "Postcopy must be started after migration has been"
1119 * we don't error if migration has finished since that would be racy
1120 * with issuing this command.
1122 atomic_set(&s
->start_postcopy
, true);
1125 /* shared migration helpers */
1127 void migrate_set_state(int *state
, int old_state
, int new_state
)
1129 assert(new_state
< MIGRATION_STATUS__MAX
);
1130 if (atomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1131 trace_migrate_set_state(MigrationStatus_str(new_state
));
1132 migrate_generate_event(new_state
);
1136 static MigrationCapabilityStatusList
*migrate_cap_add(
1137 MigrationCapabilityStatusList
*list
,
1138 MigrationCapability index
,
1141 MigrationCapabilityStatusList
*cap
;
1143 cap
= g_new0(MigrationCapabilityStatusList
, 1);
1144 cap
->value
= g_new0(MigrationCapabilityStatus
, 1);
1145 cap
->value
->capability
= index
;
1146 cap
->value
->state
= state
;
1152 void migrate_set_block_enabled(bool value
, Error
**errp
)
1154 MigrationCapabilityStatusList
*cap
;
1156 cap
= migrate_cap_add(NULL
, MIGRATION_CAPABILITY_BLOCK
, value
);
1157 qmp_migrate_set_capabilities(cap
, errp
);
1158 qapi_free_MigrationCapabilityStatusList(cap
);
1161 static void migrate_set_block_incremental(MigrationState
*s
, bool value
)
1163 s
->parameters
.block_incremental
= value
;
1166 static void block_cleanup_parameters(MigrationState
*s
)
1168 if (s
->must_remove_block_options
) {
1169 /* setting to false can never fail */
1170 migrate_set_block_enabled(false, &error_abort
);
1171 migrate_set_block_incremental(s
, false);
1172 s
->must_remove_block_options
= false;
1176 static void migrate_fd_cleanup(void *opaque
)
1178 MigrationState
*s
= opaque
;
1180 qemu_bh_delete(s
->cleanup_bh
);
1181 s
->cleanup_bh
= NULL
;
1183 qemu_savevm_state_cleanup();
1185 if (s
->to_dst_file
) {
1186 Error
*local_err
= NULL
;
1188 trace_migrate_fd_cleanup();
1189 qemu_mutex_unlock_iothread();
1190 if (s
->migration_thread_running
) {
1191 qemu_thread_join(&s
->thread
);
1192 s
->migration_thread_running
= false;
1194 qemu_mutex_lock_iothread();
1196 if (multifd_save_cleanup(&local_err
) != 0) {
1197 error_report_err(local_err
);
1199 qemu_fclose(s
->to_dst_file
);
1200 s
->to_dst_file
= NULL
;
1203 assert((s
->state
!= MIGRATION_STATUS_ACTIVE
) &&
1204 (s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
));
1206 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1207 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1208 MIGRATION_STATUS_CANCELLED
);
1212 /* It is used on info migrate. We can't free it */
1213 error_report_err(error_copy(s
->error
));
1215 notifier_list_notify(&migration_state_notifiers
, s
);
1216 block_cleanup_parameters(s
);
1219 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1221 qemu_mutex_lock(&s
->error_mutex
);
1223 s
->error
= error_copy(error
);
1225 qemu_mutex_unlock(&s
->error_mutex
);
1228 void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1230 trace_migrate_fd_error(error_get_pretty(error
));
1231 assert(s
->to_dst_file
== NULL
);
1232 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1233 MIGRATION_STATUS_FAILED
);
1234 migrate_set_error(s
, error
);
1237 static void migrate_fd_cancel(MigrationState
*s
)
1240 QEMUFile
*f
= migrate_get_current()->to_dst_file
;
1241 trace_migrate_fd_cancel();
1243 if (s
->rp_state
.from_dst_file
) {
1244 /* shutdown the rp socket, so causing the rp thread to shutdown */
1245 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1249 old_state
= s
->state
;
1250 if (!migration_is_setup_or_active(old_state
)) {
1253 /* If the migration is paused, kick it out of the pause */
1254 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1255 qemu_sem_post(&s
->pause_sem
);
1257 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1258 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1261 * If we're unlucky the migration code might be stuck somewhere in a
1262 * send/write while the network has failed and is waiting to timeout;
1263 * if we've got shutdown(2) available then we can force it to quit.
1264 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1265 * called in a bh, so there is no race against this cancel.
1267 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
1268 qemu_file_shutdown(f
);
1270 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1271 Error
*local_err
= NULL
;
1273 bdrv_invalidate_cache_all(&local_err
);
1275 error_report_err(local_err
);
1277 s
->block_inactive
= false;
1282 void add_migration_state_change_notifier(Notifier
*notify
)
1284 notifier_list_add(&migration_state_notifiers
, notify
);
1287 void remove_migration_state_change_notifier(Notifier
*notify
)
1289 notifier_remove(notify
);
1292 bool migration_in_setup(MigrationState
*s
)
1294 return s
->state
== MIGRATION_STATUS_SETUP
;
1297 bool migration_has_finished(MigrationState
*s
)
1299 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1302 bool migration_has_failed(MigrationState
*s
)
1304 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1305 s
->state
== MIGRATION_STATUS_FAILED
);
1308 bool migration_in_postcopy(void)
1310 MigrationState
*s
= migrate_get_current();
1312 return (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1315 bool migration_in_postcopy_after_devices(MigrationState
*s
)
1317 return migration_in_postcopy() && s
->postcopy_after_devices
;
1320 bool migration_is_idle(void)
1322 MigrationState
*s
= migrate_get_current();
1325 case MIGRATION_STATUS_NONE
:
1326 case MIGRATION_STATUS_CANCELLED
:
1327 case MIGRATION_STATUS_COMPLETED
:
1328 case MIGRATION_STATUS_FAILED
:
1330 case MIGRATION_STATUS_SETUP
:
1331 case MIGRATION_STATUS_CANCELLING
:
1332 case MIGRATION_STATUS_ACTIVE
:
1333 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1334 case MIGRATION_STATUS_COLO
:
1335 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1336 case MIGRATION_STATUS_DEVICE
:
1338 case MIGRATION_STATUS__MAX
:
1339 g_assert_not_reached();
1345 void migrate_init(MigrationState
*s
)
1348 * Reinitialise all migration state, except
1349 * parameters/capabilities that the user set, and
1355 s
->to_dst_file
= NULL
;
1356 s
->state
= MIGRATION_STATUS_NONE
;
1357 s
->rp_state
.from_dst_file
= NULL
;
1358 s
->rp_state
.error
= false;
1361 s
->expected_downtime
= 0;
1363 s
->start_postcopy
= false;
1364 s
->postcopy_after_devices
= false;
1365 s
->migration_thread_running
= false;
1366 error_free(s
->error
);
1369 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1371 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1373 s
->vm_was_running
= false;
1374 s
->iteration_initial_bytes
= 0;
1375 s
->threshold_size
= 0;
1378 static GSList
*migration_blockers
;
1380 int migrate_add_blocker(Error
*reason
, Error
**errp
)
1382 if (migrate_get_current()->only_migratable
) {
1383 error_propagate(errp
, error_copy(reason
));
1384 error_prepend(errp
, "disallowing migration blocker "
1385 "(--only_migratable) for: ");
1389 if (migration_is_idle()) {
1390 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
1394 error_propagate(errp
, error_copy(reason
));
1395 error_prepend(errp
, "disallowing migration blocker (migration in "
1400 void migrate_del_blocker(Error
*reason
)
1402 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
1405 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
1407 Error
*local_err
= NULL
;
1408 static bool once
= true;
1410 if (!deferred_incoming
) {
1411 error_setg(errp
, "For use with '-incoming defer'");
1415 error_setg(errp
, "The incoming migration has already been started");
1418 qemu_start_incoming_migration(uri
, &local_err
);
1421 error_propagate(errp
, local_err
);
1428 bool migration_is_blocked(Error
**errp
)
1430 if (qemu_savevm_state_blocked(errp
)) {
1434 if (migration_blockers
) {
1435 error_propagate(errp
, error_copy(migration_blockers
->data
));
1442 /* Returns true if continue to migrate, or false if error detected */
1443 static bool migrate_prepare(MigrationState
*s
, bool blk
, bool blk_inc
,
1444 bool resume
, Error
**errp
)
1446 Error
*local_err
= NULL
;
1449 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1450 error_setg(errp
, "Cannot resume if there is no "
1451 "paused migration");
1454 /* This is a resume, skip init status */
1458 if (migration_is_setup_or_active(s
->state
) ||
1459 s
->state
== MIGRATION_STATUS_CANCELLING
||
1460 s
->state
== MIGRATION_STATUS_COLO
) {
1461 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1465 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1466 error_setg(errp
, "Guest is waiting for an incoming migration");
1470 if (migration_is_blocked(errp
)) {
1474 if (blk
|| blk_inc
) {
1475 if (migrate_use_block() || migrate_use_block_incremental()) {
1476 error_setg(errp
, "Command options are incompatible with "
1477 "current migration capabilities");
1480 migrate_set_block_enabled(true, &local_err
);
1482 error_propagate(errp
, local_err
);
1485 s
->must_remove_block_options
= true;
1489 migrate_set_block_incremental(s
, true);
1497 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1498 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1499 bool has_resume
, bool resume
, Error
**errp
)
1501 Error
*local_err
= NULL
;
1502 MigrationState
*s
= migrate_get_current();
1505 if (!migrate_prepare(s
, has_blk
&& blk
, has_inc
&& inc
,
1506 has_resume
&& resume
, errp
)) {
1507 /* Error detected, put into errp */
1511 if (strstart(uri
, "tcp:", &p
)) {
1512 tcp_start_outgoing_migration(s
, p
, &local_err
);
1514 } else if (strstart(uri
, "rdma:", &p
)) {
1515 rdma_start_outgoing_migration(s
, p
, &local_err
);
1517 } else if (strstart(uri
, "exec:", &p
)) {
1518 exec_start_outgoing_migration(s
, p
, &local_err
);
1519 } else if (strstart(uri
, "unix:", &p
)) {
1520 unix_start_outgoing_migration(s
, p
, &local_err
);
1521 } else if (strstart(uri
, "fd:", &p
)) {
1522 fd_start_outgoing_migration(s
, p
, &local_err
);
1524 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1525 "a valid migration protocol");
1526 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1527 MIGRATION_STATUS_FAILED
);
1528 block_cleanup_parameters(s
);
1533 migrate_fd_error(s
, local_err
);
1534 error_propagate(errp
, local_err
);
1539 void qmp_migrate_cancel(Error
**errp
)
1541 migrate_fd_cancel(migrate_get_current());
1544 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
1546 MigrationState
*s
= migrate_get_current();
1547 if (s
->state
!= state
) {
1548 error_setg(errp
, "Migration not in expected state: %s",
1549 MigrationStatus_str(s
->state
));
1552 qemu_sem_post(&s
->pause_sem
);
1555 void qmp_migrate_set_cache_size(int64_t value
, Error
**errp
)
1557 MigrateSetParameters p
= {
1558 .has_xbzrle_cache_size
= true,
1559 .xbzrle_cache_size
= value
,
1562 qmp_migrate_set_parameters(&p
, errp
);
1565 int64_t qmp_query_migrate_cache_size(Error
**errp
)
1567 return migrate_xbzrle_cache_size();
1570 void qmp_migrate_set_speed(int64_t value
, Error
**errp
)
1572 MigrateSetParameters p
= {
1573 .has_max_bandwidth
= true,
1574 .max_bandwidth
= value
,
1577 qmp_migrate_set_parameters(&p
, errp
);
1580 void qmp_migrate_set_downtime(double value
, Error
**errp
)
1582 if (value
< 0 || value
> MAX_MIGRATE_DOWNTIME_SECONDS
) {
1583 error_setg(errp
, "Parameter 'downtime_limit' expects an integer in "
1584 "the range of 0 to %d seconds",
1585 MAX_MIGRATE_DOWNTIME_SECONDS
);
1589 value
*= 1000; /* Convert to milliseconds */
1590 value
= MAX(0, MIN(INT64_MAX
, value
));
1592 MigrateSetParameters p
= {
1593 .has_downtime_limit
= true,
1594 .downtime_limit
= value
,
1597 qmp_migrate_set_parameters(&p
, errp
);
1600 bool migrate_release_ram(void)
1604 s
= migrate_get_current();
1606 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_RELEASE_RAM
];
1609 bool migrate_postcopy_ram(void)
1613 s
= migrate_get_current();
1615 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
1618 bool migrate_postcopy(void)
1620 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1623 bool migrate_auto_converge(void)
1627 s
= migrate_get_current();
1629 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_AUTO_CONVERGE
];
1632 bool migrate_zero_blocks(void)
1636 s
= migrate_get_current();
1638 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_ZERO_BLOCKS
];
1641 bool migrate_postcopy_blocktime(void)
1645 s
= migrate_get_current();
1647 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME
];
1650 bool migrate_use_compression(void)
1654 s
= migrate_get_current();
1656 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_COMPRESS
];
1659 int migrate_compress_level(void)
1663 s
= migrate_get_current();
1665 return s
->parameters
.compress_level
;
1668 int migrate_compress_threads(void)
1672 s
= migrate_get_current();
1674 return s
->parameters
.compress_threads
;
1677 int migrate_decompress_threads(void)
1681 s
= migrate_get_current();
1683 return s
->parameters
.decompress_threads
;
1686 bool migrate_dirty_bitmaps(void)
1690 s
= migrate_get_current();
1692 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_DIRTY_BITMAPS
];
1695 bool migrate_use_events(void)
1699 s
= migrate_get_current();
1701 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_EVENTS
];
1704 bool migrate_use_multifd(void)
1708 s
= migrate_get_current();
1710 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_X_MULTIFD
];
1713 bool migrate_pause_before_switchover(void)
1717 s
= migrate_get_current();
1719 return s
->enabled_capabilities
[
1720 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER
];
1723 int migrate_multifd_channels(void)
1727 s
= migrate_get_current();
1729 return s
->parameters
.x_multifd_channels
;
1732 int migrate_multifd_page_count(void)
1736 s
= migrate_get_current();
1738 return s
->parameters
.x_multifd_page_count
;
1741 int migrate_use_xbzrle(void)
1745 s
= migrate_get_current();
1747 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_XBZRLE
];
1750 int64_t migrate_xbzrle_cache_size(void)
1754 s
= migrate_get_current();
1756 return s
->parameters
.xbzrle_cache_size
;
1759 bool migrate_use_block(void)
1763 s
= migrate_get_current();
1765 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_BLOCK
];
1768 bool migrate_use_return_path(void)
1772 s
= migrate_get_current();
1774 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_RETURN_PATH
];
1777 bool migrate_use_block_incremental(void)
1781 s
= migrate_get_current();
1783 return s
->parameters
.block_incremental
;
1786 /* migration thread support */
1788 * Something bad happened to the RP stream, mark an error
1789 * The caller shall print or trace something to indicate why
1791 static void mark_source_rp_bad(MigrationState
*s
)
1793 s
->rp_state
.error
= true;
1796 static struct rp_cmd_args
{
1797 ssize_t len
; /* -1 = variable */
1800 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1801 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1802 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1803 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1804 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1805 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1809 * Process a request for pages received on the return path,
1810 * We're allowed to send more than requested (e.g. to round to our page size)
1811 * and we don't need to send pages that have already been sent.
1813 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1814 ram_addr_t start
, size_t len
)
1816 long our_host_ps
= getpagesize();
1818 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1821 * Since we currently insist on matching page sizes, just sanity check
1822 * we're being asked for whole host pages.
1824 if (start
& (our_host_ps
-1) ||
1825 (len
& (our_host_ps
-1))) {
1826 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1827 " len: %zd", __func__
, start
, len
);
1828 mark_source_rp_bad(ms
);
1832 if (ram_save_queue_pages(rbname
, start
, len
)) {
1833 mark_source_rp_bad(ms
);
1837 /* Return true to retry, false to quit */
1838 static bool postcopy_pause_return_path_thread(MigrationState
*s
)
1840 trace_postcopy_pause_return_path();
1842 qemu_sem_wait(&s
->postcopy_pause_rp_sem
);
1844 trace_postcopy_pause_return_path_continued();
1850 * Handles messages sent on the return path towards the source VM
1853 static void *source_return_path_thread(void *opaque
)
1855 MigrationState
*ms
= opaque
;
1856 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1857 uint16_t header_len
, header_type
;
1859 uint32_t tmp32
, sibling_error
;
1860 ram_addr_t start
= 0; /* =0 to silence warning */
1861 size_t len
= 0, expected_len
;
1864 trace_source_return_path_thread_entry();
1867 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1868 migration_is_setup_or_active(ms
->state
)) {
1869 trace_source_return_path_thread_loop_top();
1870 header_type
= qemu_get_be16(rp
);
1871 header_len
= qemu_get_be16(rp
);
1873 if (qemu_file_get_error(rp
)) {
1874 mark_source_rp_bad(ms
);
1878 if (header_type
>= MIG_RP_MSG_MAX
||
1879 header_type
== MIG_RP_MSG_INVALID
) {
1880 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1881 header_type
, header_len
);
1882 mark_source_rp_bad(ms
);
1886 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1887 header_len
!= rp_cmd_args
[header_type
].len
) ||
1888 header_len
> sizeof(buf
)) {
1889 error_report("RP: Received '%s' message (0x%04x) with"
1890 "incorrect length %d expecting %zu",
1891 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1892 (size_t)rp_cmd_args
[header_type
].len
);
1893 mark_source_rp_bad(ms
);
1897 /* We know we've got a valid header by this point */
1898 res
= qemu_get_buffer(rp
, buf
, header_len
);
1899 if (res
!= header_len
) {
1900 error_report("RP: Failed reading data for message 0x%04x"
1901 " read %d expected %d",
1902 header_type
, res
, header_len
);
1903 mark_source_rp_bad(ms
);
1907 /* OK, we have the message and the data */
1908 switch (header_type
) {
1909 case MIG_RP_MSG_SHUT
:
1910 sibling_error
= ldl_be_p(buf
);
1911 trace_source_return_path_thread_shut(sibling_error
);
1912 if (sibling_error
) {
1913 error_report("RP: Sibling indicated error %d", sibling_error
);
1914 mark_source_rp_bad(ms
);
1917 * We'll let the main thread deal with closing the RP
1918 * we could do a shutdown(2) on it, but we're the only user
1919 * anyway, so there's nothing gained.
1923 case MIG_RP_MSG_PONG
:
1924 tmp32
= ldl_be_p(buf
);
1925 trace_source_return_path_thread_pong(tmp32
);
1928 case MIG_RP_MSG_REQ_PAGES
:
1929 start
= ldq_be_p(buf
);
1930 len
= ldl_be_p(buf
+ 8);
1931 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1934 case MIG_RP_MSG_REQ_PAGES_ID
:
1935 expected_len
= 12 + 1; /* header + termination */
1937 if (header_len
>= expected_len
) {
1938 start
= ldq_be_p(buf
);
1939 len
= ldl_be_p(buf
+ 8);
1940 /* Now we expect an idstr */
1941 tmp32
= buf
[12]; /* Length of the following idstr */
1942 buf
[13 + tmp32
] = '\0';
1943 expected_len
+= tmp32
;
1945 if (header_len
!= expected_len
) {
1946 error_report("RP: Req_Page_id with length %d expecting %zd",
1947 header_len
, expected_len
);
1948 mark_source_rp_bad(ms
);
1951 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1960 res
= qemu_file_get_error(rp
);
1964 * Maybe there is something we can do: it looks like a
1965 * network down issue, and we pause for a recovery.
1967 if (postcopy_pause_return_path_thread(ms
)) {
1968 /* Reload rp, reset the rest */
1969 rp
= ms
->rp_state
.from_dst_file
;
1970 ms
->rp_state
.error
= false;
1975 trace_source_return_path_thread_bad_end();
1976 mark_source_rp_bad(ms
);
1979 trace_source_return_path_thread_end();
1980 ms
->rp_state
.from_dst_file
= NULL
;
1985 static int open_return_path_on_source(MigrationState
*ms
,
1989 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
1990 if (!ms
->rp_state
.from_dst_file
) {
1994 trace_open_return_path_on_source();
1996 if (!create_thread
) {
2001 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
2002 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
2004 trace_open_return_path_on_source_continue();
2009 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2010 static int await_return_path_close_on_source(MigrationState
*ms
)
2013 * If this is a normal exit then the destination will send a SHUT and the
2014 * rp_thread will exit, however if there's an error we need to cause
2017 if (qemu_file_get_error(ms
->to_dst_file
) && ms
->rp_state
.from_dst_file
) {
2019 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2020 * waiting for the destination.
2022 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
2023 mark_source_rp_bad(ms
);
2025 trace_await_return_path_close_on_source_joining();
2026 qemu_thread_join(&ms
->rp_state
.rp_thread
);
2027 trace_await_return_path_close_on_source_close();
2028 return ms
->rp_state
.error
;
2032 * Switch from normal iteration to postcopy
2033 * Returns non-0 on error
2035 static int postcopy_start(MigrationState
*ms
)
2038 QIOChannelBuffer
*bioc
;
2040 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2041 bool restart_block
= false;
2042 int cur_state
= MIGRATION_STATUS_ACTIVE
;
2043 if (!migrate_pause_before_switchover()) {
2044 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
2045 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2048 trace_postcopy_start();
2049 qemu_mutex_lock_iothread();
2050 trace_postcopy_start_set_run();
2052 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
2053 global_state_store();
2054 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2059 ret
= migration_maybe_pause(ms
, &cur_state
,
2060 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2065 ret
= bdrv_inactivate_all();
2069 restart_block
= true;
2072 * Cause any non-postcopiable, but iterative devices to
2073 * send out their final data.
2075 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
2078 * in Finish migrate and with the io-lock held everything should
2079 * be quiet, but we've potentially still got dirty pages and we
2080 * need to tell the destination to throw any pages it's already received
2083 if (migrate_postcopy_ram()) {
2084 if (ram_postcopy_send_discard_bitmap(ms
)) {
2085 error_report("postcopy send discard bitmap failed");
2091 * send rest of state - note things that are doing postcopy
2092 * will notice we're in POSTCOPY_ACTIVE and not actually
2093 * wrap their state up here
2095 qemu_file_set_rate_limit(ms
->to_dst_file
, INT64_MAX
);
2096 if (migrate_postcopy_ram()) {
2097 /* Ping just for debugging, helps line traces up */
2098 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2102 * While loading the device state we may trigger page transfer
2103 * requests and the fd must be free to process those, and thus
2104 * the destination must read the whole device state off the fd before
2105 * it starts processing it. Unfortunately the ad-hoc migration format
2106 * doesn't allow the destination to know the size to read without fully
2107 * parsing it through each devices load-state code (especially the open
2108 * coded devices that use get/put).
2109 * So we wrap the device state up in a package with a length at the start;
2110 * to do this we use a qemu_buf to hold the whole of the device state.
2112 bioc
= qio_channel_buffer_new(4096);
2113 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2114 fb
= qemu_fopen_channel_output(QIO_CHANNEL(bioc
));
2115 object_unref(OBJECT(bioc
));
2118 * Make sure the receiver can get incoming pages before we send the rest
2121 qemu_savevm_send_postcopy_listen(fb
);
2123 qemu_savevm_state_complete_precopy(fb
, false, false);
2124 if (migrate_postcopy_ram()) {
2125 qemu_savevm_send_ping(fb
, 3);
2128 qemu_savevm_send_postcopy_run(fb
);
2130 /* <><> end of stuff going into the package */
2132 /* Last point of recovery; as soon as we send the package the destination
2133 * can open devices and potentially start running.
2134 * Lets just check again we've not got any errors.
2136 ret
= qemu_file_get_error(ms
->to_dst_file
);
2138 error_report("postcopy_start: Migration stream errored (pre package)");
2142 restart_block
= false;
2144 /* Now send that blob */
2145 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2150 /* Send a notify to give a chance for anything that needs to happen
2151 * at the transition to postcopy and after the device state; in particular
2152 * spice needs to trigger a transition now
2154 ms
->postcopy_after_devices
= true;
2155 notifier_list_notify(&migration_state_notifiers
, ms
);
2157 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
2159 qemu_mutex_unlock_iothread();
2161 if (migrate_postcopy_ram()) {
2163 * Although this ping is just for debug, it could potentially be
2164 * used for getting a better measurement of downtime at the source.
2166 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2169 if (migrate_release_ram()) {
2170 ram_postcopy_migrated_memory_release(ms
);
2173 ret
= qemu_file_get_error(ms
->to_dst_file
);
2175 error_report("postcopy_start: Migration stream errored");
2176 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2177 MIGRATION_STATUS_FAILED
);
2185 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2186 MIGRATION_STATUS_FAILED
);
2187 if (restart_block
) {
2188 /* A failure happened early enough that we know the destination hasn't
2189 * accessed block devices, so we're safe to recover.
2191 Error
*local_err
= NULL
;
2193 bdrv_invalidate_cache_all(&local_err
);
2195 error_report_err(local_err
);
2198 qemu_mutex_unlock_iothread();
2203 * migration_maybe_pause: Pause if required to by
2204 * migrate_pause_before_switchover called with the iothread locked
2205 * Returns: 0 on success
2207 static int migration_maybe_pause(MigrationState
*s
,
2208 int *current_active_state
,
2211 if (!migrate_pause_before_switchover()) {
2215 /* Since leaving this state is not atomic with posting the semaphore
2216 * it's possible that someone could have issued multiple migrate_continue
2217 * and the semaphore is incorrectly positive at this point;
2218 * the docs say it's undefined to reinit a semaphore that's already
2219 * init'd, so use timedwait to eat up any existing posts.
2221 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2222 /* This block intentionally left blank */
2225 qemu_mutex_unlock_iothread();
2226 migrate_set_state(&s
->state
, *current_active_state
,
2227 MIGRATION_STATUS_PRE_SWITCHOVER
);
2228 qemu_sem_wait(&s
->pause_sem
);
2229 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2231 *current_active_state
= new_state
;
2232 qemu_mutex_lock_iothread();
2234 return s
->state
== new_state
? 0 : -EINVAL
;
2238 * migration_completion: Used by migration_thread when there's not much left.
2239 * The caller 'breaks' the loop when this returns.
2241 * @s: Current migration state
2243 static void migration_completion(MigrationState
*s
)
2246 int current_active_state
= s
->state
;
2248 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2249 qemu_mutex_lock_iothread();
2250 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2251 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
2252 s
->vm_was_running
= runstate_is_running();
2253 ret
= global_state_store();
2256 bool inactivate
= !migrate_colo_enabled();
2257 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2259 ret
= migration_maybe_pause(s
, ¤t_active_state
,
2260 MIGRATION_STATUS_DEVICE
);
2263 qemu_file_set_rate_limit(s
->to_dst_file
, INT64_MAX
);
2264 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2267 if (inactivate
&& ret
>= 0) {
2268 s
->block_inactive
= true;
2271 qemu_mutex_unlock_iothread();
2276 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2277 trace_migration_completion_postcopy_end();
2279 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2280 trace_migration_completion_postcopy_end_after_complete();
2284 * If rp was opened we must clean up the thread before
2285 * cleaning everything else up (since if there are no failures
2286 * it will wait for the destination to send it's status in
2289 if (s
->rp_state
.from_dst_file
) {
2291 trace_migration_return_path_end_before();
2292 rp_error
= await_return_path_close_on_source(s
);
2293 trace_migration_return_path_end_after(rp_error
);
2295 goto fail_invalidate
;
2299 if (qemu_file_get_error(s
->to_dst_file
)) {
2300 trace_migration_completion_file_err();
2301 goto fail_invalidate
;
2304 if (!migrate_colo_enabled()) {
2305 migrate_set_state(&s
->state
, current_active_state
,
2306 MIGRATION_STATUS_COMPLETED
);
2312 /* If not doing postcopy, vm_start() will be called: let's regain
2313 * control on images.
2315 if (s
->state
== MIGRATION_STATUS_ACTIVE
||
2316 s
->state
== MIGRATION_STATUS_DEVICE
) {
2317 Error
*local_err
= NULL
;
2319 qemu_mutex_lock_iothread();
2320 bdrv_invalidate_cache_all(&local_err
);
2322 error_report_err(local_err
);
2324 s
->block_inactive
= false;
2326 qemu_mutex_unlock_iothread();
2330 migrate_set_state(&s
->state
, current_active_state
,
2331 MIGRATION_STATUS_FAILED
);
2334 bool migrate_colo_enabled(void)
2336 MigrationState
*s
= migrate_get_current();
2337 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_X_COLO
];
2340 typedef enum MigThrError
{
2341 /* No error detected */
2342 MIG_THR_ERR_NONE
= 0,
2343 /* Detected error, but resumed successfully */
2344 MIG_THR_ERR_RECOVERED
= 1,
2345 /* Detected fatal error, need to exit */
2346 MIG_THR_ERR_FATAL
= 2,
2349 /* Return zero if success, or <0 for error */
2350 static int postcopy_do_resume(MigrationState
*s
)
2352 /* TODO: do the resume logic */
2357 * We don't return until we are in a safe state to continue current
2358 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2359 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2361 static MigThrError
postcopy_pause(MigrationState
*s
)
2363 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2366 migrate_set_state(&s
->state
, s
->state
,
2367 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2369 /* Current channel is possibly broken. Release it. */
2370 assert(s
->to_dst_file
);
2371 qemu_file_shutdown(s
->to_dst_file
);
2372 qemu_fclose(s
->to_dst_file
);
2373 s
->to_dst_file
= NULL
;
2375 error_report("Detected IO failure for postcopy. "
2376 "Migration paused.");
2379 * We wait until things fixed up. Then someone will setup the
2380 * status back for us.
2382 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2383 qemu_sem_wait(&s
->postcopy_pause_sem
);
2386 if (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2387 /* Woken up by a recover procedure. Give it a shot */
2390 * Firstly, let's wake up the return path now, with a new
2391 * return path channel.
2393 qemu_sem_post(&s
->postcopy_pause_rp_sem
);
2395 /* Do the resume logic */
2396 if (postcopy_do_resume(s
) == 0) {
2397 /* Let's continue! */
2398 trace_postcopy_pause_continued();
2399 return MIG_THR_ERR_RECOVERED
;
2402 * Something wrong happened during the recovery, let's
2403 * pause again. Pause is always better than throwing
2409 /* This is not right... Time to quit. */
2410 return MIG_THR_ERR_FATAL
;
2415 static MigThrError
migration_detect_error(MigrationState
*s
)
2419 /* Try to detect any file errors */
2420 ret
= qemu_file_get_error(s
->to_dst_file
);
2423 /* Everything is fine */
2424 return MIG_THR_ERR_NONE
;
2427 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
== -EIO
) {
2429 * For postcopy, we allow the network to be down for a
2430 * while. After that, it can be continued by a
2433 return postcopy_pause(s
);
2436 * For precopy (or postcopy with error outside IO), we fail
2439 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
2440 trace_migration_thread_file_err();
2442 /* Time to stop the migration, now. */
2443 return MIG_THR_ERR_FATAL
;
2447 static void migration_calculate_complete(MigrationState
*s
)
2449 uint64_t bytes
= qemu_ftell(s
->to_dst_file
);
2450 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2452 s
->total_time
= end_time
- s
->start_time
;
2455 * It's still not set, so we are precopy migration. For
2456 * postcopy, downtime is calculated during postcopy_start().
2458 s
->downtime
= end_time
- s
->downtime_start
;
2461 if (s
->total_time
) {
2462 s
->mbps
= ((double) bytes
* 8.0) / s
->total_time
/ 1000;
2466 static void migration_update_counters(MigrationState
*s
,
2467 int64_t current_time
)
2469 uint64_t transferred
, time_spent
;
2472 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
2476 transferred
= qemu_ftell(s
->to_dst_file
) - s
->iteration_initial_bytes
;
2477 time_spent
= current_time
- s
->iteration_start_time
;
2478 bandwidth
= (double)transferred
/ time_spent
;
2479 s
->threshold_size
= bandwidth
* s
->parameters
.downtime_limit
;
2481 s
->mbps
= (((double) transferred
* 8.0) /
2482 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
2485 * if we haven't sent anything, we don't want to
2486 * recalculate. 10000 is a small enough number for our purposes
2488 if (ram_counters
.dirty_pages_rate
&& transferred
> 10000) {
2489 s
->expected_downtime
= ram_counters
.dirty_pages_rate
*
2490 qemu_target_page_size() / bandwidth
;
2493 qemu_file_reset_rate_limit(s
->to_dst_file
);
2495 s
->iteration_start_time
= current_time
;
2496 s
->iteration_initial_bytes
= qemu_ftell(s
->to_dst_file
);
2498 trace_migrate_transferred(transferred
, time_spent
,
2499 bandwidth
, s
->threshold_size
);
2502 /* Migration thread iteration status */
2504 MIG_ITERATE_RESUME
, /* Resume current iteration */
2505 MIG_ITERATE_SKIP
, /* Skip current iteration */
2506 MIG_ITERATE_BREAK
, /* Break the loop */
2510 * Return true if continue to the next iteration directly, false
2513 static MigIterateState
migration_iteration_run(MigrationState
*s
)
2515 uint64_t pending_size
, pend_pre
, pend_compat
, pend_post
;
2516 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
2518 qemu_savevm_state_pending(s
->to_dst_file
, s
->threshold_size
, &pend_pre
,
2519 &pend_compat
, &pend_post
);
2520 pending_size
= pend_pre
+ pend_compat
+ pend_post
;
2522 trace_migrate_pending(pending_size
, s
->threshold_size
,
2523 pend_pre
, pend_compat
, pend_post
);
2525 if (pending_size
&& pending_size
>= s
->threshold_size
) {
2526 /* Still a significant amount to transfer */
2527 if (migrate_postcopy() && !in_postcopy
&&
2528 pend_pre
<= s
->threshold_size
&&
2529 atomic_read(&s
->start_postcopy
)) {
2530 if (postcopy_start(s
)) {
2531 error_report("%s: postcopy failed to start", __func__
);
2533 return MIG_ITERATE_SKIP
;
2535 /* Just another iteration step */
2536 qemu_savevm_state_iterate(s
->to_dst_file
,
2537 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2539 trace_migration_thread_low_pending(pending_size
);
2540 migration_completion(s
);
2541 return MIG_ITERATE_BREAK
;
2544 return MIG_ITERATE_RESUME
;
2547 static void migration_iteration_finish(MigrationState
*s
)
2549 /* If we enabled cpu throttling for auto-converge, turn it off. */
2550 cpu_throttle_stop();
2552 qemu_mutex_lock_iothread();
2554 case MIGRATION_STATUS_COMPLETED
:
2555 migration_calculate_complete(s
);
2556 runstate_set(RUN_STATE_POSTMIGRATE
);
2559 case MIGRATION_STATUS_ACTIVE
:
2561 * We should really assert here, but since it's during
2562 * migration, let's try to reduce the usage of assertions.
2564 if (!migrate_colo_enabled()) {
2565 error_report("%s: critical error: calling COLO code without "
2566 "COLO enabled", __func__
);
2568 migrate_start_colo_process(s
);
2570 * Fixme: we will run VM in COLO no matter its old running state.
2571 * After exited COLO, we will keep running.
2573 s
->vm_was_running
= true;
2575 case MIGRATION_STATUS_FAILED
:
2576 case MIGRATION_STATUS_CANCELLED
:
2577 if (s
->vm_was_running
) {
2580 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
2581 runstate_set(RUN_STATE_POSTMIGRATE
);
2587 /* Should not reach here, but if so, forgive the VM. */
2588 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
2591 qemu_bh_schedule(s
->cleanup_bh
);
2592 qemu_mutex_unlock_iothread();
2596 * Master migration thread on the source VM.
2597 * It drives the migration and pumps the data down the outgoing channel.
2599 static void *migration_thread(void *opaque
)
2601 MigrationState
*s
= opaque
;
2602 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
2603 MigThrError thr_error
;
2605 rcu_register_thread();
2607 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2609 qemu_savevm_state_header(s
->to_dst_file
);
2612 * If we opened the return path, we need to make sure dst has it
2615 if (s
->rp_state
.from_dst_file
) {
2616 /* Now tell the dest that it should open its end so it can reply */
2617 qemu_savevm_send_open_return_path(s
->to_dst_file
);
2619 /* And do a ping that will make stuff easier to debug */
2620 qemu_savevm_send_ping(s
->to_dst_file
, 1);
2623 if (migrate_postcopy()) {
2625 * Tell the destination that we *might* want to do postcopy later;
2626 * if the other end can't do postcopy it should fail now, nice and
2629 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
2632 qemu_savevm_state_setup(s
->to_dst_file
);
2634 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
2635 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
2636 MIGRATION_STATUS_ACTIVE
);
2638 trace_migration_thread_setup_complete();
2640 while (s
->state
== MIGRATION_STATUS_ACTIVE
||
2641 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2642 int64_t current_time
;
2644 if (!qemu_file_rate_limit(s
->to_dst_file
)) {
2645 MigIterateState iter_state
= migration_iteration_run(s
);
2646 if (iter_state
== MIG_ITERATE_SKIP
) {
2648 } else if (iter_state
== MIG_ITERATE_BREAK
) {
2654 * Try to detect any kind of failures, and see whether we
2655 * should stop the migration now.
2657 thr_error
= migration_detect_error(s
);
2658 if (thr_error
== MIG_THR_ERR_FATAL
) {
2659 /* Stop migration */
2661 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
2663 * Just recovered from a e.g. network failure, reset all
2664 * the local variables. This is important to avoid
2665 * breaking transferred_bytes and bandwidth calculation
2667 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2668 s
->iteration_initial_bytes
= 0;
2671 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2673 migration_update_counters(s
, current_time
);
2675 if (qemu_file_rate_limit(s
->to_dst_file
)) {
2676 /* usleep expects microseconds */
2677 g_usleep((s
->iteration_start_time
+ BUFFER_DELAY
-
2678 current_time
) * 1000);
2682 trace_migration_thread_after_loop();
2683 migration_iteration_finish(s
);
2684 rcu_unregister_thread();
2688 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
2691 bool resume
= s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
;
2693 s
->expected_downtime
= s
->parameters
.downtime_limit
;
2694 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
2696 migrate_fd_error(s
, error_in
);
2697 migrate_fd_cleanup(s
);
2702 /* This is a resumed migration */
2703 rate_limit
= INT64_MAX
;
2705 /* This is a fresh new migration */
2706 rate_limit
= s
->parameters
.max_bandwidth
/ XFER_LIMIT_RATIO
;
2707 s
->expected_downtime
= s
->parameters
.downtime_limit
;
2708 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
2710 /* Notify before starting migration thread */
2711 notifier_list_notify(&migration_state_notifiers
, s
);
2714 qemu_file_set_rate_limit(s
->to_dst_file
, rate_limit
);
2715 qemu_file_set_blocking(s
->to_dst_file
, true);
2718 * Open the return path. For postcopy, it is used exclusively. For
2719 * precopy, only if user specified "return-path" capability would
2720 * QEMU uses the return path.
2722 if (migrate_postcopy_ram() || migrate_use_return_path()) {
2723 if (open_return_path_on_source(s
, !resume
)) {
2724 error_report("Unable to open return-path for postcopy");
2725 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
2726 migrate_fd_cleanup(s
);
2732 /* Wakeup the main migration thread to do the recovery */
2733 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
2734 MIGRATION_STATUS_POSTCOPY_RECOVER
);
2735 qemu_sem_post(&s
->postcopy_pause_sem
);
2739 if (multifd_save_setup() != 0) {
2740 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
2741 MIGRATION_STATUS_FAILED
);
2742 migrate_fd_cleanup(s
);
2745 qemu_thread_create(&s
->thread
, "live_migration", migration_thread
, s
,
2746 QEMU_THREAD_JOINABLE
);
2747 s
->migration_thread_running
= true;
2750 void migration_global_dump(Monitor
*mon
)
2752 MigrationState
*ms
= migrate_get_current();
2754 monitor_printf(mon
, "globals:\n");
2755 monitor_printf(mon
, "store-global-state: %s\n",
2756 ms
->store_global_state
? "on" : "off");
2757 monitor_printf(mon
, "only-migratable: %s\n",
2758 ms
->only_migratable
? "on" : "off");
2759 monitor_printf(mon
, "send-configuration: %s\n",
2760 ms
->send_configuration
? "on" : "off");
2761 monitor_printf(mon
, "send-section-footer: %s\n",
2762 ms
->send_section_footer
? "on" : "off");
2765 #define DEFINE_PROP_MIG_CAP(name, x) \
2766 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2768 static Property migration_properties
[] = {
2769 DEFINE_PROP_BOOL("store-global-state", MigrationState
,
2770 store_global_state
, true),
2771 DEFINE_PROP_BOOL("only-migratable", MigrationState
, only_migratable
, false),
2772 DEFINE_PROP_BOOL("send-configuration", MigrationState
,
2773 send_configuration
, true),
2774 DEFINE_PROP_BOOL("send-section-footer", MigrationState
,
2775 send_section_footer
, true),
2777 /* Migration parameters */
2778 DEFINE_PROP_UINT8("x-compress-level", MigrationState
,
2779 parameters
.compress_level
,
2780 DEFAULT_MIGRATE_COMPRESS_LEVEL
),
2781 DEFINE_PROP_UINT8("x-compress-threads", MigrationState
,
2782 parameters
.compress_threads
,
2783 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT
),
2784 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState
,
2785 parameters
.decompress_threads
,
2786 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT
),
2787 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState
,
2788 parameters
.cpu_throttle_initial
,
2789 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL
),
2790 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState
,
2791 parameters
.cpu_throttle_increment
,
2792 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT
),
2793 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState
,
2794 parameters
.max_bandwidth
, MAX_THROTTLE
),
2795 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState
,
2796 parameters
.downtime_limit
,
2797 DEFAULT_MIGRATE_SET_DOWNTIME
),
2798 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState
,
2799 parameters
.x_checkpoint_delay
,
2800 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY
),
2801 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState
,
2802 parameters
.x_multifd_channels
,
2803 DEFAULT_MIGRATE_MULTIFD_CHANNELS
),
2804 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState
,
2805 parameters
.x_multifd_page_count
,
2806 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT
),
2807 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState
,
2808 parameters
.xbzrle_cache_size
,
2809 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE
),
2811 /* Migration capabilities */
2812 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE
),
2813 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL
),
2814 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE
),
2815 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS
),
2816 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS
),
2817 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS
),
2818 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM
),
2819 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO
),
2820 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM
),
2821 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK
),
2822 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH
),
2823 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD
),
2825 DEFINE_PROP_END_OF_LIST(),
2828 static void migration_class_init(ObjectClass
*klass
, void *data
)
2830 DeviceClass
*dc
= DEVICE_CLASS(klass
);
2832 dc
->user_creatable
= false;
2833 dc
->props
= migration_properties
;
2836 static void migration_instance_finalize(Object
*obj
)
2838 MigrationState
*ms
= MIGRATION_OBJ(obj
);
2839 MigrationParameters
*params
= &ms
->parameters
;
2841 qemu_mutex_destroy(&ms
->error_mutex
);
2842 g_free(params
->tls_hostname
);
2843 g_free(params
->tls_creds
);
2844 qemu_sem_destroy(&ms
->pause_sem
);
2845 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
2846 qemu_sem_destroy(&ms
->postcopy_pause_rp_sem
);
2847 error_free(ms
->error
);
2850 static void migration_instance_init(Object
*obj
)
2852 MigrationState
*ms
= MIGRATION_OBJ(obj
);
2853 MigrationParameters
*params
= &ms
->parameters
;
2855 ms
->state
= MIGRATION_STATUS_NONE
;
2857 qemu_sem_init(&ms
->pause_sem
, 0);
2858 qemu_mutex_init(&ms
->error_mutex
);
2860 params
->tls_hostname
= g_strdup("");
2861 params
->tls_creds
= g_strdup("");
2863 /* Set has_* up only for parameter checks */
2864 params
->has_compress_level
= true;
2865 params
->has_compress_threads
= true;
2866 params
->has_decompress_threads
= true;
2867 params
->has_cpu_throttle_initial
= true;
2868 params
->has_cpu_throttle_increment
= true;
2869 params
->has_max_bandwidth
= true;
2870 params
->has_downtime_limit
= true;
2871 params
->has_x_checkpoint_delay
= true;
2872 params
->has_block_incremental
= true;
2873 params
->has_x_multifd_channels
= true;
2874 params
->has_x_multifd_page_count
= true;
2875 params
->has_xbzrle_cache_size
= true;
2877 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
2878 qemu_sem_init(&ms
->postcopy_pause_rp_sem
, 0);
2882 * Return true if check pass, false otherwise. Error will be put
2883 * inside errp if provided.
2885 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
2887 MigrationCapabilityStatusList
*head
= NULL
;
2888 /* Assuming all off */
2889 bool cap_list
[MIGRATION_CAPABILITY__MAX
] = { 0 }, ret
;
2892 if (!migrate_params_check(&ms
->parameters
, errp
)) {
2896 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
2897 if (ms
->enabled_capabilities
[i
]) {
2898 head
= migrate_cap_add(head
, i
, true);
2902 ret
= migrate_caps_check(cap_list
, head
, errp
);
2904 /* It works with head == NULL */
2905 qapi_free_MigrationCapabilityStatusList(head
);
2910 static const TypeInfo migration_type
= {
2911 .name
= TYPE_MIGRATION
,
2913 * NOTE: TYPE_MIGRATION is not really a device, as the object is
2914 * not created using qdev_create(), it is not attached to the qdev
2915 * device tree, and it is never realized.
2917 * TODO: Make this TYPE_OBJECT once QOM provides something like
2918 * TYPE_DEVICE's "-global" properties.
2920 .parent
= TYPE_DEVICE
,
2921 .class_init
= migration_class_init
,
2922 .class_size
= sizeof(MigrationClass
),
2923 .instance_size
= sizeof(MigrationState
),
2924 .instance_init
= migration_instance_init
,
2925 .instance_finalize
= migration_instance_finalize
,
2928 static void register_migration_types(void)
2930 type_register_static(&migration_type
);
2933 type_init(register_migration_types
);