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/qmp/qerror.h"
34 #include "qapi/util.h"
37 #include "postcopy-ram.h"
38 #include "qemu/thread.h"
39 #include "qmp-commands.h"
41 #include "qapi-event.h"
42 #include "exec/target_page.h"
43 #include "io/channel-buffer.h"
44 #include "migration/colo.h"
46 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
48 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
50 #define BUFFER_DELAY 100
51 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
53 /* Time in milliseconds we are allowed to stop the source,
54 * for sending the last part */
55 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
57 /* Maximum migrate downtime set to 2000 seconds */
58 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
59 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
61 /* Default compression thread count */
62 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
63 /* Default decompression thread count, usually decompression is at
64 * least 4 times as fast as compression.*/
65 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
66 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
67 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
68 /* Define default autoconverge cpu throttle migration parameters */
69 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
70 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
72 /* Migration XBZRLE default cache size */
73 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
75 /* The delay time (in ms) between two COLO checkpoints
76 * Note: Please change this default value to 10000 when we support hybrid mode.
78 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
80 static NotifierList migration_state_notifiers
=
81 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
83 static bool deferred_incoming
;
85 /* Messages sent on the return path from destination to source */
86 enum mig_rp_message_type
{
87 MIG_RP_MSG_INVALID
= 0, /* Must be 0 */
88 MIG_RP_MSG_SHUT
, /* sibling will not send any more RP messages */
89 MIG_RP_MSG_PONG
, /* Response to a PING; data (seq: be32 ) */
91 MIG_RP_MSG_REQ_PAGES_ID
, /* data (start: be64, len: be32, id: string) */
92 MIG_RP_MSG_REQ_PAGES
, /* data (start: be64, len: be32) */
97 /* When we add fault tolerance, we could have several
98 migrations at once. For now we don't need to add
99 dynamic creation of migration */
102 MigrationState
*migrate_get_current(void)
105 static MigrationState current_migration
= {
106 .state
= MIGRATION_STATUS_NONE
,
107 .xbzrle_cache_size
= DEFAULT_MIGRATE_CACHE_SIZE
,
110 .compress_level
= DEFAULT_MIGRATE_COMPRESS_LEVEL
,
111 .compress_threads
= DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT
,
112 .decompress_threads
= DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT
,
113 .cpu_throttle_initial
= DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL
,
114 .cpu_throttle_increment
= DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT
,
115 .max_bandwidth
= MAX_THROTTLE
,
116 .downtime_limit
= DEFAULT_MIGRATE_SET_DOWNTIME
,
117 .x_checkpoint_delay
= DEFAULT_MIGRATE_X_CHECKPOINT_DELAY
,
122 current_migration
.parameters
.tls_creds
= g_strdup("");
123 current_migration
.parameters
.tls_hostname
= g_strdup("");
126 return ¤t_migration
;
129 MigrationIncomingState
*migration_incoming_get_current(void)
132 static MigrationIncomingState mis_current
;
135 mis_current
.state
= MIGRATION_STATUS_NONE
;
136 memset(&mis_current
, 0, sizeof(MigrationIncomingState
));
137 qemu_mutex_init(&mis_current
.rp_mutex
);
138 qemu_event_init(&mis_current
.main_thread_load_event
, false);
144 void migration_incoming_state_destroy(void)
146 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
148 if (mis
->to_src_file
) {
149 /* Tell source that we are done */
150 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
151 qemu_fclose(mis
->to_src_file
);
152 mis
->to_src_file
= NULL
;
155 if (mis
->from_src_file
) {
156 qemu_fclose(mis
->from_src_file
);
157 mis
->from_src_file
= NULL
;
160 qemu_event_destroy(&mis
->main_thread_load_event
);
163 static void migrate_generate_event(int new_state
)
165 if (migrate_use_events()) {
166 qapi_event_send_migration(new_state
, &error_abort
);
171 * Called on -incoming with a defer: uri.
172 * The migration can be started later after any parameters have been
175 static void deferred_incoming_migration(Error
**errp
)
177 if (deferred_incoming
) {
178 error_setg(errp
, "Incoming migration already deferred");
180 deferred_incoming
= true;
184 * Send a message on the return channel back to the source
187 static void migrate_send_rp_message(MigrationIncomingState
*mis
,
188 enum mig_rp_message_type message_type
,
189 uint16_t len
, void *data
)
191 trace_migrate_send_rp_message((int)message_type
, len
);
192 qemu_mutex_lock(&mis
->rp_mutex
);
193 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
194 qemu_put_be16(mis
->to_src_file
, len
);
195 qemu_put_buffer(mis
->to_src_file
, data
, len
);
196 qemu_fflush(mis
->to_src_file
);
197 qemu_mutex_unlock(&mis
->rp_mutex
);
200 /* Request a range of pages from the source VM at the given
202 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
203 * as the last request (a name must have been given previously)
204 * Start: Address offset within the RB
205 * Len: Length in bytes required - must be a multiple of pagesize
207 void migrate_send_rp_req_pages(MigrationIncomingState
*mis
, const char *rbname
,
208 ram_addr_t start
, size_t len
)
210 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
211 size_t msglen
= 12; /* start + len */
213 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
214 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
217 int rbname_len
= strlen(rbname
);
218 assert(rbname_len
< 256);
220 bufc
[msglen
++] = rbname_len
;
221 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
222 msglen
+= rbname_len
;
223 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES_ID
, msglen
, bufc
);
225 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES
, msglen
, bufc
);
229 void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
233 qapi_event_send_migration(MIGRATION_STATUS_SETUP
, &error_abort
);
234 if (!strcmp(uri
, "defer")) {
235 deferred_incoming_migration(errp
);
236 } else if (strstart(uri
, "tcp:", &p
)) {
237 tcp_start_incoming_migration(p
, errp
);
239 } else if (strstart(uri
, "rdma:", &p
)) {
240 rdma_start_incoming_migration(p
, errp
);
242 } else if (strstart(uri
, "exec:", &p
)) {
243 exec_start_incoming_migration(p
, errp
);
244 } else if (strstart(uri
, "unix:", &p
)) {
245 unix_start_incoming_migration(p
, errp
);
246 } else if (strstart(uri
, "fd:", &p
)) {
247 fd_start_incoming_migration(p
, errp
);
249 error_setg(errp
, "unknown migration protocol: %s", uri
);
253 static void process_incoming_migration_bh(void *opaque
)
255 Error
*local_err
= NULL
;
256 MigrationIncomingState
*mis
= opaque
;
258 /* Make sure all file formats flush their mutable metadata.
259 * If we get an error here, just don't restart the VM yet. */
260 bdrv_invalidate_cache_all(&local_err
);
262 error_report_err(local_err
);
268 * This must happen after all error conditions are dealt with and
269 * we're sure the VM is going to be running on this host.
271 qemu_announce_self();
273 /* If global state section was not received or we are in running
274 state, we need to obey autostart. Any other state is set with
277 if (!global_state_received() ||
278 global_state_get_runstate() == RUN_STATE_RUNNING
) {
282 runstate_set(RUN_STATE_PAUSED
);
285 runstate_set(global_state_get_runstate());
287 migrate_decompress_threads_join();
289 * This must happen after any state changes since as soon as an external
290 * observer sees this event they might start to prod at the VM assuming
293 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
294 MIGRATION_STATUS_COMPLETED
);
295 qemu_bh_delete(mis
->bh
);
296 migration_incoming_state_destroy();
299 static void process_incoming_migration_co(void *opaque
)
301 QEMUFile
*f
= opaque
;
302 MigrationIncomingState
*mis
= migration_incoming_get_current();
306 mis
->from_src_file
= f
;
307 mis
->largest_page_size
= qemu_ram_pagesize_largest();
308 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
309 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
310 MIGRATION_STATUS_ACTIVE
);
311 ret
= qemu_loadvm_state(f
);
313 ps
= postcopy_state_get();
314 trace_process_incoming_migration_co_end(ret
, ps
);
315 if (ps
!= POSTCOPY_INCOMING_NONE
) {
316 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
318 * Where a migration had postcopy enabled (and thus went to advise)
319 * but managed to complete within the precopy period, we can use
322 postcopy_ram_incoming_cleanup(mis
);
323 } else if (ret
>= 0) {
325 * Postcopy was started, cleanup should happen at the end of the
328 trace_process_incoming_migration_co_postcopy_end_main();
331 /* Else if something went wrong then just fall out of the normal exit */
334 /* we get COLO info, and know if we are in COLO mode */
335 if (!ret
&& migration_incoming_enable_colo()) {
336 mis
->migration_incoming_co
= qemu_coroutine_self();
337 qemu_thread_create(&mis
->colo_incoming_thread
, "COLO incoming",
338 colo_process_incoming_thread
, mis
, QEMU_THREAD_JOINABLE
);
339 mis
->have_colo_incoming_thread
= true;
340 qemu_coroutine_yield();
342 /* Wait checkpoint incoming thread exit before free resource */
343 qemu_thread_join(&mis
->colo_incoming_thread
);
347 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
348 MIGRATION_STATUS_FAILED
);
349 error_report("load of migration failed: %s", strerror(-ret
));
350 migrate_decompress_threads_join();
354 free_xbzrle_decoded_buf();
356 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
357 qemu_bh_schedule(mis
->bh
);
360 void migration_fd_process_incoming(QEMUFile
*f
)
362 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, f
);
364 migrate_decompress_threads_create();
365 qemu_file_set_blocking(f
, false);
366 qemu_coroutine_enter(co
);
370 * Send a 'SHUT' message on the return channel with the given value
371 * to indicate that we've finished with the RP. Non-0 value indicates
374 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
379 buf
= cpu_to_be32(value
);
380 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
384 * Send a 'PONG' message on the return channel with the given value
385 * (normally in response to a 'PING')
387 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
392 buf
= cpu_to_be32(value
);
393 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
396 MigrationCapabilityStatusList
*qmp_query_migrate_capabilities(Error
**errp
)
398 MigrationCapabilityStatusList
*head
= NULL
;
399 MigrationCapabilityStatusList
*caps
;
400 MigrationState
*s
= migrate_get_current();
403 caps
= NULL
; /* silence compiler warning */
404 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
405 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
406 if (i
== MIGRATION_CAPABILITY_BLOCK
) {
410 if (i
== MIGRATION_CAPABILITY_X_COLO
&& !colo_supported()) {
414 head
= g_malloc0(sizeof(*caps
));
417 caps
->next
= g_malloc0(sizeof(*caps
));
421 g_malloc(sizeof(*caps
->value
));
422 caps
->value
->capability
= i
;
423 caps
->value
->state
= s
->enabled_capabilities
[i
];
429 MigrationParameters
*qmp_query_migrate_parameters(Error
**errp
)
431 MigrationParameters
*params
;
432 MigrationState
*s
= migrate_get_current();
434 params
= g_malloc0(sizeof(*params
));
435 params
->has_compress_level
= true;
436 params
->compress_level
= s
->parameters
.compress_level
;
437 params
->has_compress_threads
= true;
438 params
->compress_threads
= s
->parameters
.compress_threads
;
439 params
->has_decompress_threads
= true;
440 params
->decompress_threads
= s
->parameters
.decompress_threads
;
441 params
->has_cpu_throttle_initial
= true;
442 params
->cpu_throttle_initial
= s
->parameters
.cpu_throttle_initial
;
443 params
->has_cpu_throttle_increment
= true;
444 params
->cpu_throttle_increment
= s
->parameters
.cpu_throttle_increment
;
445 params
->has_tls_creds
= !!s
->parameters
.tls_creds
;
446 params
->tls_creds
= g_strdup(s
->parameters
.tls_creds
);
447 params
->has_tls_hostname
= !!s
->parameters
.tls_hostname
;
448 params
->tls_hostname
= g_strdup(s
->parameters
.tls_hostname
);
449 params
->has_max_bandwidth
= true;
450 params
->max_bandwidth
= s
->parameters
.max_bandwidth
;
451 params
->has_downtime_limit
= true;
452 params
->downtime_limit
= s
->parameters
.downtime_limit
;
453 params
->has_x_checkpoint_delay
= true;
454 params
->x_checkpoint_delay
= s
->parameters
.x_checkpoint_delay
;
455 params
->has_block_incremental
= true;
456 params
->block_incremental
= s
->parameters
.block_incremental
;
462 * Return true if we're already in the middle of a migration
463 * (i.e. any of the active or setup states)
465 static bool migration_is_setup_or_active(int state
)
468 case MIGRATION_STATUS_ACTIVE
:
469 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
470 case MIGRATION_STATUS_SETUP
:
479 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
481 info
->has_ram
= true;
482 info
->ram
= g_malloc0(sizeof(*info
->ram
));
483 info
->ram
->transferred
= ram_counters
.transferred
;
484 info
->ram
->total
= ram_bytes_total();
485 info
->ram
->duplicate
= ram_counters
.duplicate
;
486 /* legacy value. It is not used anymore */
487 info
->ram
->skipped
= 0;
488 info
->ram
->normal
= ram_counters
.normal
;
489 info
->ram
->normal_bytes
= ram_counters
.normal
*
490 qemu_target_page_size();
491 info
->ram
->mbps
= s
->mbps
;
492 info
->ram
->dirty_sync_count
= ram_counters
.dirty_sync_count
;
493 info
->ram
->postcopy_requests
= ram_counters
.postcopy_requests
;
494 info
->ram
->page_size
= qemu_target_page_size();
496 if (migrate_use_xbzrle()) {
497 info
->has_xbzrle_cache
= true;
498 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
499 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
500 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
501 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
502 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
503 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
504 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
507 if (cpu_throttle_active()) {
508 info
->has_cpu_throttle_percentage
= true;
509 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
512 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
513 info
->ram
->remaining
= ram_bytes_remaining();
514 info
->ram
->dirty_pages_rate
= ram_counters
.dirty_pages_rate
;
518 static void populate_disk_info(MigrationInfo
*info
)
520 if (blk_mig_active()) {
521 info
->has_disk
= true;
522 info
->disk
= g_malloc0(sizeof(*info
->disk
));
523 info
->disk
->transferred
= blk_mig_bytes_transferred();
524 info
->disk
->remaining
= blk_mig_bytes_remaining();
525 info
->disk
->total
= blk_mig_bytes_total();
529 MigrationInfo
*qmp_query_migrate(Error
**errp
)
531 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
532 MigrationState
*s
= migrate_get_current();
535 case MIGRATION_STATUS_NONE
:
536 /* no migration has happened ever */
538 case MIGRATION_STATUS_SETUP
:
539 info
->has_status
= true;
540 info
->has_total_time
= false;
542 case MIGRATION_STATUS_ACTIVE
:
543 case MIGRATION_STATUS_CANCELLING
:
544 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
545 /* TODO add some postcopy stats */
546 info
->has_status
= true;
547 info
->has_total_time
= true;
548 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
550 info
->has_expected_downtime
= true;
551 info
->expected_downtime
= s
->expected_downtime
;
552 info
->has_setup_time
= true;
553 info
->setup_time
= s
->setup_time
;
555 populate_ram_info(info
, s
);
556 populate_disk_info(info
);
558 case MIGRATION_STATUS_COLO
:
559 info
->has_status
= true;
560 /* TODO: display COLO specific information (checkpoint info etc.) */
562 case MIGRATION_STATUS_COMPLETED
:
563 info
->has_status
= true;
564 info
->has_total_time
= true;
565 info
->total_time
= s
->total_time
;
566 info
->has_downtime
= true;
567 info
->downtime
= s
->downtime
;
568 info
->has_setup_time
= true;
569 info
->setup_time
= s
->setup_time
;
571 populate_ram_info(info
, s
);
573 case MIGRATION_STATUS_FAILED
:
574 info
->has_status
= true;
576 info
->has_error_desc
= true;
577 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
580 case MIGRATION_STATUS_CANCELLED
:
581 info
->has_status
= true;
584 info
->status
= s
->state
;
589 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList
*params
,
592 MigrationState
*s
= migrate_get_current();
593 MigrationCapabilityStatusList
*cap
;
594 bool old_postcopy_cap
= migrate_postcopy_ram();
596 if (migration_is_setup_or_active(s
->state
)) {
597 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
601 for (cap
= params
; cap
; cap
= cap
->next
) {
602 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
603 if (cap
->value
->capability
== MIGRATION_CAPABILITY_BLOCK
604 && cap
->value
->state
) {
605 error_setg(errp
, "QEMU compiled without old-style (blk/-b, inc/-i) "
607 error_append_hint(errp
, "Use drive_mirror+NBD instead.\n");
611 if (cap
->value
->capability
== MIGRATION_CAPABILITY_X_COLO
) {
612 if (!colo_supported()) {
613 error_setg(errp
, "COLO is not currently supported, please"
614 " configure with --enable-colo option in order to"
615 " support COLO feature");
619 s
->enabled_capabilities
[cap
->value
->capability
] = cap
->value
->state
;
622 if (migrate_postcopy_ram()) {
623 if (migrate_use_compression()) {
624 /* The decompression threads asynchronously write into RAM
625 * rather than use the atomic copies needed to avoid
626 * userfaulting. It should be possible to fix the decompression
627 * threads for compatibility in future.
629 error_report("Postcopy is not currently compatible with "
631 s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
] =
634 /* This check is reasonably expensive, so only when it's being
635 * set the first time, also it's only the destination that needs
638 if (!old_postcopy_cap
&& runstate_check(RUN_STATE_INMIGRATE
) &&
639 !postcopy_ram_supported_by_host()) {
640 /* postcopy_ram_supported_by_host will have emitted a more
643 error_report("Postcopy is not supported");
644 s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
] =
650 void qmp_migrate_set_parameters(MigrationParameters
*params
, Error
**errp
)
652 MigrationState
*s
= migrate_get_current();
654 if (params
->has_compress_level
&&
655 (params
->compress_level
< 0 || params
->compress_level
> 9)) {
656 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "compress_level",
657 "is invalid, it should be in the range of 0 to 9");
660 if (params
->has_compress_threads
&&
661 (params
->compress_threads
< 1 || params
->compress_threads
> 255)) {
662 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
664 "is invalid, it should be in the range of 1 to 255");
667 if (params
->has_decompress_threads
&&
668 (params
->decompress_threads
< 1 || params
->decompress_threads
> 255)) {
669 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
670 "decompress_threads",
671 "is invalid, it should be in the range of 1 to 255");
674 if (params
->has_cpu_throttle_initial
&&
675 (params
->cpu_throttle_initial
< 1 ||
676 params
->cpu_throttle_initial
> 99)) {
677 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
678 "cpu_throttle_initial",
679 "an integer in the range of 1 to 99");
682 if (params
->has_cpu_throttle_increment
&&
683 (params
->cpu_throttle_increment
< 1 ||
684 params
->cpu_throttle_increment
> 99)) {
685 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
686 "cpu_throttle_increment",
687 "an integer in the range of 1 to 99");
690 if (params
->has_max_bandwidth
&&
691 (params
->max_bandwidth
< 0 || params
->max_bandwidth
> SIZE_MAX
)) {
692 error_setg(errp
, "Parameter 'max_bandwidth' expects an integer in the"
693 " range of 0 to %zu bytes/second", SIZE_MAX
);
696 if (params
->has_downtime_limit
&&
697 (params
->downtime_limit
< 0 ||
698 params
->downtime_limit
> MAX_MIGRATE_DOWNTIME
)) {
699 error_setg(errp
, "Parameter 'downtime_limit' expects an integer in "
700 "the range of 0 to %d milliseconds",
701 MAX_MIGRATE_DOWNTIME
);
704 if (params
->has_x_checkpoint_delay
&& (params
->x_checkpoint_delay
< 0)) {
705 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
706 "x_checkpoint_delay",
707 "is invalid, it should be positive");
710 if (params
->has_compress_level
) {
711 s
->parameters
.compress_level
= params
->compress_level
;
713 if (params
->has_compress_threads
) {
714 s
->parameters
.compress_threads
= params
->compress_threads
;
716 if (params
->has_decompress_threads
) {
717 s
->parameters
.decompress_threads
= params
->decompress_threads
;
719 if (params
->has_cpu_throttle_initial
) {
720 s
->parameters
.cpu_throttle_initial
= params
->cpu_throttle_initial
;
722 if (params
->has_cpu_throttle_increment
) {
723 s
->parameters
.cpu_throttle_increment
= params
->cpu_throttle_increment
;
725 if (params
->has_tls_creds
) {
726 g_free(s
->parameters
.tls_creds
);
727 s
->parameters
.tls_creds
= g_strdup(params
->tls_creds
);
729 if (params
->has_tls_hostname
) {
730 g_free(s
->parameters
.tls_hostname
);
731 s
->parameters
.tls_hostname
= g_strdup(params
->tls_hostname
);
733 if (params
->has_max_bandwidth
) {
734 s
->parameters
.max_bandwidth
= params
->max_bandwidth
;
735 if (s
->to_dst_file
) {
736 qemu_file_set_rate_limit(s
->to_dst_file
,
737 s
->parameters
.max_bandwidth
/ XFER_LIMIT_RATIO
);
740 if (params
->has_downtime_limit
) {
741 s
->parameters
.downtime_limit
= params
->downtime_limit
;
744 if (params
->has_x_checkpoint_delay
) {
745 s
->parameters
.x_checkpoint_delay
= params
->x_checkpoint_delay
;
746 if (migration_in_colo_state()) {
747 colo_checkpoint_notify(s
);
750 if (params
->has_block_incremental
) {
751 s
->parameters
.block_incremental
= params
->block_incremental
;
756 void qmp_migrate_start_postcopy(Error
**errp
)
758 MigrationState
*s
= migrate_get_current();
760 if (!migrate_postcopy_ram()) {
761 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
762 " the start of migration");
766 if (s
->state
== MIGRATION_STATUS_NONE
) {
767 error_setg(errp
, "Postcopy must be started after migration has been"
772 * we don't error if migration has finished since that would be racy
773 * with issuing this command.
775 atomic_set(&s
->start_postcopy
, true);
778 /* shared migration helpers */
780 void migrate_set_state(int *state
, int old_state
, int new_state
)
782 if (atomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
783 trace_migrate_set_state(new_state
);
784 migrate_generate_event(new_state
);
788 void migrate_set_block_enabled(bool value
, Error
**errp
)
790 MigrationCapabilityStatusList
*cap
;
792 cap
= g_new0(MigrationCapabilityStatusList
, 1);
793 cap
->value
= g_new0(MigrationCapabilityStatus
, 1);
794 cap
->value
->capability
= MIGRATION_CAPABILITY_BLOCK
;
795 cap
->value
->state
= value
;
796 qmp_migrate_set_capabilities(cap
, errp
);
797 qapi_free_MigrationCapabilityStatusList(cap
);
800 static void migrate_set_block_incremental(MigrationState
*s
, bool value
)
802 s
->parameters
.block_incremental
= value
;
805 static void block_cleanup_parameters(MigrationState
*s
)
807 if (s
->must_remove_block_options
) {
808 /* setting to false can never fail */
809 migrate_set_block_enabled(false, &error_abort
);
810 migrate_set_block_incremental(s
, false);
811 s
->must_remove_block_options
= false;
815 static void migrate_fd_cleanup(void *opaque
)
817 MigrationState
*s
= opaque
;
819 qemu_bh_delete(s
->cleanup_bh
);
820 s
->cleanup_bh
= NULL
;
822 if (s
->to_dst_file
) {
823 trace_migrate_fd_cleanup();
824 qemu_mutex_unlock_iothread();
825 if (s
->migration_thread_running
) {
826 qemu_thread_join(&s
->thread
);
827 s
->migration_thread_running
= false;
829 qemu_mutex_lock_iothread();
831 migrate_compress_threads_join();
832 qemu_fclose(s
->to_dst_file
);
833 s
->to_dst_file
= NULL
;
836 assert((s
->state
!= MIGRATION_STATUS_ACTIVE
) &&
837 (s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
));
839 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
840 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
841 MIGRATION_STATUS_CANCELLED
);
844 notifier_list_notify(&migration_state_notifiers
, s
);
845 block_cleanup_parameters(s
);
848 void migrate_fd_error(MigrationState
*s
, const Error
*error
)
850 trace_migrate_fd_error(error_get_pretty(error
));
851 assert(s
->to_dst_file
== NULL
);
852 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
853 MIGRATION_STATUS_FAILED
);
855 s
->error
= error_copy(error
);
857 notifier_list_notify(&migration_state_notifiers
, s
);
858 block_cleanup_parameters(s
);
861 static void migrate_fd_cancel(MigrationState
*s
)
864 QEMUFile
*f
= migrate_get_current()->to_dst_file
;
865 trace_migrate_fd_cancel();
867 if (s
->rp_state
.from_dst_file
) {
868 /* shutdown the rp socket, so causing the rp thread to shutdown */
869 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
873 old_state
= s
->state
;
874 if (!migration_is_setup_or_active(old_state
)) {
877 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
878 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
881 * If we're unlucky the migration code might be stuck somewhere in a
882 * send/write while the network has failed and is waiting to timeout;
883 * if we've got shutdown(2) available then we can force it to quit.
884 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
885 * called in a bh, so there is no race against this cancel.
887 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
888 qemu_file_shutdown(f
);
890 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
891 Error
*local_err
= NULL
;
893 bdrv_invalidate_cache_all(&local_err
);
895 error_report_err(local_err
);
897 s
->block_inactive
= false;
900 block_cleanup_parameters(s
);
903 void add_migration_state_change_notifier(Notifier
*notify
)
905 notifier_list_add(&migration_state_notifiers
, notify
);
908 void remove_migration_state_change_notifier(Notifier
*notify
)
910 notifier_remove(notify
);
913 bool migration_in_setup(MigrationState
*s
)
915 return s
->state
== MIGRATION_STATUS_SETUP
;
918 bool migration_has_finished(MigrationState
*s
)
920 return s
->state
== MIGRATION_STATUS_COMPLETED
;
923 bool migration_has_failed(MigrationState
*s
)
925 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
926 s
->state
== MIGRATION_STATUS_FAILED
);
929 bool migration_in_postcopy(void)
931 MigrationState
*s
= migrate_get_current();
933 return (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
936 bool migration_in_postcopy_after_devices(MigrationState
*s
)
938 return migration_in_postcopy() && s
->postcopy_after_devices
;
941 bool migration_is_idle(void)
943 MigrationState
*s
= migrate_get_current();
946 case MIGRATION_STATUS_NONE
:
947 case MIGRATION_STATUS_CANCELLED
:
948 case MIGRATION_STATUS_COMPLETED
:
949 case MIGRATION_STATUS_FAILED
:
951 case MIGRATION_STATUS_SETUP
:
952 case MIGRATION_STATUS_CANCELLING
:
953 case MIGRATION_STATUS_ACTIVE
:
954 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
955 case MIGRATION_STATUS_COLO
:
957 case MIGRATION_STATUS__MAX
:
958 g_assert_not_reached();
964 MigrationState
*migrate_init(void)
966 MigrationState
*s
= migrate_get_current();
969 * Reinitialise all migration state, except
970 * parameters/capabilities that the user set, and
976 s
->to_dst_file
= NULL
;
977 s
->state
= MIGRATION_STATUS_NONE
;
978 s
->rp_state
.from_dst_file
= NULL
;
979 s
->rp_state
.error
= false;
982 s
->expected_downtime
= 0;
984 s
->start_postcopy
= false;
985 s
->postcopy_after_devices
= false;
986 s
->migration_thread_running
= false;
987 error_free(s
->error
);
990 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
992 s
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
996 static GSList
*migration_blockers
;
998 int migrate_add_blocker(Error
*reason
, Error
**errp
)
1000 if (only_migratable
) {
1001 error_propagate(errp
, error_copy(reason
));
1002 error_prepend(errp
, "disallowing migration blocker "
1003 "(--only_migratable) for: ");
1007 if (migration_is_idle()) {
1008 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
1012 error_propagate(errp
, error_copy(reason
));
1013 error_prepend(errp
, "disallowing migration blocker (migration in "
1018 void migrate_del_blocker(Error
*reason
)
1020 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
1023 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
1025 Error
*local_err
= NULL
;
1026 static bool once
= true;
1028 if (!deferred_incoming
) {
1029 error_setg(errp
, "For use with '-incoming defer'");
1033 error_setg(errp
, "The incoming migration has already been started");
1036 qemu_start_incoming_migration(uri
, &local_err
);
1039 error_propagate(errp
, local_err
);
1046 bool migration_is_blocked(Error
**errp
)
1048 if (qemu_savevm_state_blocked(errp
)) {
1052 if (migration_blockers
) {
1053 error_propagate(errp
, error_copy(migration_blockers
->data
));
1060 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1061 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1064 Error
*local_err
= NULL
;
1065 MigrationState
*s
= migrate_get_current();
1068 if (migration_is_setup_or_active(s
->state
) ||
1069 s
->state
== MIGRATION_STATUS_CANCELLING
||
1070 s
->state
== MIGRATION_STATUS_COLO
) {
1071 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1074 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1075 error_setg(errp
, "Guest is waiting for an incoming migration");
1079 if (migration_is_blocked(errp
)) {
1083 if ((has_blk
&& blk
) || (has_inc
&& inc
)) {
1084 if (migrate_use_block() || migrate_use_block_incremental()) {
1085 error_setg(errp
, "Command options are incompatible with "
1086 "current migration capabilities");
1089 migrate_set_block_enabled(true, &local_err
);
1091 error_propagate(errp
, local_err
);
1094 s
->must_remove_block_options
= true;
1097 if (has_inc
&& inc
) {
1098 migrate_set_block_incremental(s
, true);
1103 if (strstart(uri
, "tcp:", &p
)) {
1104 tcp_start_outgoing_migration(s
, p
, &local_err
);
1106 } else if (strstart(uri
, "rdma:", &p
)) {
1107 rdma_start_outgoing_migration(s
, p
, &local_err
);
1109 } else if (strstart(uri
, "exec:", &p
)) {
1110 exec_start_outgoing_migration(s
, p
, &local_err
);
1111 } else if (strstart(uri
, "unix:", &p
)) {
1112 unix_start_outgoing_migration(s
, p
, &local_err
);
1113 } else if (strstart(uri
, "fd:", &p
)) {
1114 fd_start_outgoing_migration(s
, p
, &local_err
);
1116 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1117 "a valid migration protocol");
1118 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1119 MIGRATION_STATUS_FAILED
);
1124 migrate_fd_error(s
, local_err
);
1125 error_propagate(errp
, local_err
);
1130 void qmp_migrate_cancel(Error
**errp
)
1132 migrate_fd_cancel(migrate_get_current());
1135 void qmp_migrate_set_cache_size(int64_t value
, Error
**errp
)
1137 MigrationState
*s
= migrate_get_current();
1140 /* Check for truncation */
1141 if (value
!= (size_t)value
) {
1142 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1143 "exceeding address space");
1147 /* Cache should not be larger than guest ram size */
1148 if (value
> ram_bytes_total()) {
1149 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1150 "exceeds guest ram size ");
1154 new_size
= xbzrle_cache_resize(value
);
1156 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1157 "is smaller than page size");
1161 s
->xbzrle_cache_size
= new_size
;
1164 int64_t qmp_query_migrate_cache_size(Error
**errp
)
1166 return migrate_xbzrle_cache_size();
1169 void qmp_migrate_set_speed(int64_t value
, Error
**errp
)
1171 MigrationParameters p
= {
1172 .has_max_bandwidth
= true,
1173 .max_bandwidth
= value
,
1176 qmp_migrate_set_parameters(&p
, errp
);
1179 void qmp_migrate_set_downtime(double value
, Error
**errp
)
1181 if (value
< 0 || value
> MAX_MIGRATE_DOWNTIME_SECONDS
) {
1182 error_setg(errp
, "Parameter 'downtime_limit' expects an integer in "
1183 "the range of 0 to %d seconds",
1184 MAX_MIGRATE_DOWNTIME_SECONDS
);
1188 value
*= 1000; /* Convert to milliseconds */
1189 value
= MAX(0, MIN(INT64_MAX
, value
));
1191 MigrationParameters p
= {
1192 .has_downtime_limit
= true,
1193 .downtime_limit
= value
,
1196 qmp_migrate_set_parameters(&p
, errp
);
1199 bool migrate_release_ram(void)
1203 s
= migrate_get_current();
1205 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_RELEASE_RAM
];
1208 bool migrate_postcopy_ram(void)
1212 s
= migrate_get_current();
1214 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
1217 bool migrate_auto_converge(void)
1221 s
= migrate_get_current();
1223 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_AUTO_CONVERGE
];
1226 bool migrate_zero_blocks(void)
1230 s
= migrate_get_current();
1232 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_ZERO_BLOCKS
];
1235 bool migrate_use_compression(void)
1239 s
= migrate_get_current();
1241 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_COMPRESS
];
1244 int migrate_compress_level(void)
1248 s
= migrate_get_current();
1250 return s
->parameters
.compress_level
;
1253 int migrate_compress_threads(void)
1257 s
= migrate_get_current();
1259 return s
->parameters
.compress_threads
;
1262 int migrate_decompress_threads(void)
1266 s
= migrate_get_current();
1268 return s
->parameters
.decompress_threads
;
1271 bool migrate_use_events(void)
1275 s
= migrate_get_current();
1277 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_EVENTS
];
1280 int migrate_use_xbzrle(void)
1284 s
= migrate_get_current();
1286 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_XBZRLE
];
1289 int64_t migrate_xbzrle_cache_size(void)
1293 s
= migrate_get_current();
1295 return s
->xbzrle_cache_size
;
1298 bool migrate_use_block(void)
1302 s
= migrate_get_current();
1304 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_BLOCK
];
1307 bool migrate_use_block_incremental(void)
1311 s
= migrate_get_current();
1313 return s
->parameters
.block_incremental
;
1316 /* migration thread support */
1318 * Something bad happened to the RP stream, mark an error
1319 * The caller shall print or trace something to indicate why
1321 static void mark_source_rp_bad(MigrationState
*s
)
1323 s
->rp_state
.error
= true;
1326 static struct rp_cmd_args
{
1327 ssize_t len
; /* -1 = variable */
1330 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1331 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1332 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1333 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1334 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1335 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1339 * Process a request for pages received on the return path,
1340 * We're allowed to send more than requested (e.g. to round to our page size)
1341 * and we don't need to send pages that have already been sent.
1343 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1344 ram_addr_t start
, size_t len
)
1346 long our_host_ps
= getpagesize();
1348 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1351 * Since we currently insist on matching page sizes, just sanity check
1352 * we're being asked for whole host pages.
1354 if (start
& (our_host_ps
-1) ||
1355 (len
& (our_host_ps
-1))) {
1356 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1357 " len: %zd", __func__
, start
, len
);
1358 mark_source_rp_bad(ms
);
1362 if (ram_save_queue_pages(rbname
, start
, len
)) {
1363 mark_source_rp_bad(ms
);
1368 * Handles messages sent on the return path towards the source VM
1371 static void *source_return_path_thread(void *opaque
)
1373 MigrationState
*ms
= opaque
;
1374 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1375 uint16_t header_len
, header_type
;
1377 uint32_t tmp32
, sibling_error
;
1378 ram_addr_t start
= 0; /* =0 to silence warning */
1379 size_t len
= 0, expected_len
;
1382 trace_source_return_path_thread_entry();
1383 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1384 migration_is_setup_or_active(ms
->state
)) {
1385 trace_source_return_path_thread_loop_top();
1386 header_type
= qemu_get_be16(rp
);
1387 header_len
= qemu_get_be16(rp
);
1389 if (header_type
>= MIG_RP_MSG_MAX
||
1390 header_type
== MIG_RP_MSG_INVALID
) {
1391 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1392 header_type
, header_len
);
1393 mark_source_rp_bad(ms
);
1397 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1398 header_len
!= rp_cmd_args
[header_type
].len
) ||
1399 header_len
> sizeof(buf
)) {
1400 error_report("RP: Received '%s' message (0x%04x) with"
1401 "incorrect length %d expecting %zu",
1402 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1403 (size_t)rp_cmd_args
[header_type
].len
);
1404 mark_source_rp_bad(ms
);
1408 /* We know we've got a valid header by this point */
1409 res
= qemu_get_buffer(rp
, buf
, header_len
);
1410 if (res
!= header_len
) {
1411 error_report("RP: Failed reading data for message 0x%04x"
1412 " read %d expected %d",
1413 header_type
, res
, header_len
);
1414 mark_source_rp_bad(ms
);
1418 /* OK, we have the message and the data */
1419 switch (header_type
) {
1420 case MIG_RP_MSG_SHUT
:
1421 sibling_error
= ldl_be_p(buf
);
1422 trace_source_return_path_thread_shut(sibling_error
);
1423 if (sibling_error
) {
1424 error_report("RP: Sibling indicated error %d", sibling_error
);
1425 mark_source_rp_bad(ms
);
1428 * We'll let the main thread deal with closing the RP
1429 * we could do a shutdown(2) on it, but we're the only user
1430 * anyway, so there's nothing gained.
1434 case MIG_RP_MSG_PONG
:
1435 tmp32
= ldl_be_p(buf
);
1436 trace_source_return_path_thread_pong(tmp32
);
1439 case MIG_RP_MSG_REQ_PAGES
:
1440 start
= ldq_be_p(buf
);
1441 len
= ldl_be_p(buf
+ 8);
1442 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1445 case MIG_RP_MSG_REQ_PAGES_ID
:
1446 expected_len
= 12 + 1; /* header + termination */
1448 if (header_len
>= expected_len
) {
1449 start
= ldq_be_p(buf
);
1450 len
= ldl_be_p(buf
+ 8);
1451 /* Now we expect an idstr */
1452 tmp32
= buf
[12]; /* Length of the following idstr */
1453 buf
[13 + tmp32
] = '\0';
1454 expected_len
+= tmp32
;
1456 if (header_len
!= expected_len
) {
1457 error_report("RP: Req_Page_id with length %d expecting %zd",
1458 header_len
, expected_len
);
1459 mark_source_rp_bad(ms
);
1462 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1469 if (qemu_file_get_error(rp
)) {
1470 trace_source_return_path_thread_bad_end();
1471 mark_source_rp_bad(ms
);
1474 trace_source_return_path_thread_end();
1476 ms
->rp_state
.from_dst_file
= NULL
;
1481 static int open_return_path_on_source(MigrationState
*ms
)
1484 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
1485 if (!ms
->rp_state
.from_dst_file
) {
1489 trace_open_return_path_on_source();
1490 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
1491 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
1493 trace_open_return_path_on_source_continue();
1498 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1499 static int await_return_path_close_on_source(MigrationState
*ms
)
1502 * If this is a normal exit then the destination will send a SHUT and the
1503 * rp_thread will exit, however if there's an error we need to cause
1506 if (qemu_file_get_error(ms
->to_dst_file
) && ms
->rp_state
.from_dst_file
) {
1508 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1509 * waiting for the destination.
1511 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
1512 mark_source_rp_bad(ms
);
1514 trace_await_return_path_close_on_source_joining();
1515 qemu_thread_join(&ms
->rp_state
.rp_thread
);
1516 trace_await_return_path_close_on_source_close();
1517 return ms
->rp_state
.error
;
1521 * Switch from normal iteration to postcopy
1522 * Returns non-0 on error
1524 static int postcopy_start(MigrationState
*ms
, bool *old_vm_running
)
1527 QIOChannelBuffer
*bioc
;
1529 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1530 bool restart_block
= false;
1531 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
1532 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1534 trace_postcopy_start();
1535 qemu_mutex_lock_iothread();
1536 trace_postcopy_start_set_run();
1538 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1539 *old_vm_running
= runstate_is_running();
1540 global_state_store();
1541 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1546 ret
= bdrv_inactivate_all();
1550 restart_block
= true;
1553 * Cause any non-postcopiable, but iterative devices to
1554 * send out their final data.
1556 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
1559 * in Finish migrate and with the io-lock held everything should
1560 * be quiet, but we've potentially still got dirty pages and we
1561 * need to tell the destination to throw any pages it's already received
1564 if (ram_postcopy_send_discard_bitmap(ms
)) {
1565 error_report("postcopy send discard bitmap failed");
1570 * send rest of state - note things that are doing postcopy
1571 * will notice we're in POSTCOPY_ACTIVE and not actually
1572 * wrap their state up here
1574 qemu_file_set_rate_limit(ms
->to_dst_file
, INT64_MAX
);
1575 /* Ping just for debugging, helps line traces up */
1576 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
1579 * While loading the device state we may trigger page transfer
1580 * requests and the fd must be free to process those, and thus
1581 * the destination must read the whole device state off the fd before
1582 * it starts processing it. Unfortunately the ad-hoc migration format
1583 * doesn't allow the destination to know the size to read without fully
1584 * parsing it through each devices load-state code (especially the open
1585 * coded devices that use get/put).
1586 * So we wrap the device state up in a package with a length at the start;
1587 * to do this we use a qemu_buf to hold the whole of the device state.
1589 bioc
= qio_channel_buffer_new(4096);
1590 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
1591 fb
= qemu_fopen_channel_output(QIO_CHANNEL(bioc
));
1592 object_unref(OBJECT(bioc
));
1595 * Make sure the receiver can get incoming pages before we send the rest
1598 qemu_savevm_send_postcopy_listen(fb
);
1600 qemu_savevm_state_complete_precopy(fb
, false, false);
1601 qemu_savevm_send_ping(fb
, 3);
1603 qemu_savevm_send_postcopy_run(fb
);
1605 /* <><> end of stuff going into the package */
1607 /* Last point of recovery; as soon as we send the package the destination
1608 * can open devices and potentially start running.
1609 * Lets just check again we've not got any errors.
1611 ret
= qemu_file_get_error(ms
->to_dst_file
);
1613 error_report("postcopy_start: Migration stream errored (pre package)");
1617 restart_block
= false;
1619 /* Now send that blob */
1620 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
1625 /* Send a notify to give a chance for anything that needs to happen
1626 * at the transition to postcopy and after the device state; in particular
1627 * spice needs to trigger a transition now
1629 ms
->postcopy_after_devices
= true;
1630 notifier_list_notify(&migration_state_notifiers
, ms
);
1632 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
1634 qemu_mutex_unlock_iothread();
1637 * Although this ping is just for debug, it could potentially be
1638 * used for getting a better measurement of downtime at the source.
1640 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
1642 if (migrate_release_ram()) {
1643 ram_postcopy_migrated_memory_release(ms
);
1646 ret
= qemu_file_get_error(ms
->to_dst_file
);
1648 error_report("postcopy_start: Migration stream errored");
1649 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1650 MIGRATION_STATUS_FAILED
);
1658 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1659 MIGRATION_STATUS_FAILED
);
1660 if (restart_block
) {
1661 /* A failure happened early enough that we know the destination hasn't
1662 * accessed block devices, so we're safe to recover.
1664 Error
*local_err
= NULL
;
1666 bdrv_invalidate_cache_all(&local_err
);
1668 error_report_err(local_err
);
1671 qemu_mutex_unlock_iothread();
1676 * migration_completion: Used by migration_thread when there's not much left.
1677 * The caller 'breaks' the loop when this returns.
1679 * @s: Current migration state
1680 * @current_active_state: The migration state we expect to be in
1681 * @*old_vm_running: Pointer to old_vm_running flag
1682 * @*start_time: Pointer to time to update
1684 static void migration_completion(MigrationState
*s
, int current_active_state
,
1685 bool *old_vm_running
,
1686 int64_t *start_time
)
1690 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1691 qemu_mutex_lock_iothread();
1692 *start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1693 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1694 *old_vm_running
= runstate_is_running();
1695 ret
= global_state_store();
1698 bool inactivate
= !migrate_colo_enabled();
1699 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1701 qemu_file_set_rate_limit(s
->to_dst_file
, INT64_MAX
);
1702 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
1705 if (inactivate
&& ret
>= 0) {
1706 s
->block_inactive
= true;
1709 qemu_mutex_unlock_iothread();
1714 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1715 trace_migration_completion_postcopy_end();
1717 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
1718 trace_migration_completion_postcopy_end_after_complete();
1722 * If rp was opened we must clean up the thread before
1723 * cleaning everything else up (since if there are no failures
1724 * it will wait for the destination to send it's status in
1727 if (s
->rp_state
.from_dst_file
) {
1729 trace_migration_return_path_end_before();
1730 rp_error
= await_return_path_close_on_source(s
);
1731 trace_migration_return_path_end_after(rp_error
);
1733 goto fail_invalidate
;
1737 if (qemu_file_get_error(s
->to_dst_file
)) {
1738 trace_migration_completion_file_err();
1739 goto fail_invalidate
;
1742 if (!migrate_colo_enabled()) {
1743 migrate_set_state(&s
->state
, current_active_state
,
1744 MIGRATION_STATUS_COMPLETED
);
1750 /* If not doing postcopy, vm_start() will be called: let's regain
1751 * control on images.
1753 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1754 Error
*local_err
= NULL
;
1756 qemu_mutex_lock_iothread();
1757 bdrv_invalidate_cache_all(&local_err
);
1759 error_report_err(local_err
);
1761 s
->block_inactive
= false;
1763 qemu_mutex_unlock_iothread();
1767 migrate_set_state(&s
->state
, current_active_state
,
1768 MIGRATION_STATUS_FAILED
);
1771 bool migrate_colo_enabled(void)
1773 MigrationState
*s
= migrate_get_current();
1774 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_X_COLO
];
1778 * Master migration thread on the source VM.
1779 * It drives the migration and pumps the data down the outgoing channel.
1781 static void *migration_thread(void *opaque
)
1783 MigrationState
*s
= opaque
;
1784 /* Used by the bandwidth calcs, updated later */
1785 int64_t initial_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1786 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
1787 int64_t initial_bytes
= 0;
1789 * The final stage happens when the remaining data is smaller than
1790 * this threshold; it's calculated from the requested downtime and
1791 * measured bandwidth
1793 int64_t threshold_size
= 0;
1794 int64_t start_time
= initial_time
;
1796 bool old_vm_running
= false;
1797 bool entered_postcopy
= false;
1798 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1799 enum MigrationStatus current_active_state
= MIGRATION_STATUS_ACTIVE
;
1800 bool enable_colo
= migrate_colo_enabled();
1802 rcu_register_thread();
1804 qemu_savevm_state_header(s
->to_dst_file
);
1807 * If we opened the return path, we need to make sure dst has it
1810 if (s
->rp_state
.from_dst_file
) {
1811 /* Now tell the dest that it should open its end so it can reply */
1812 qemu_savevm_send_open_return_path(s
->to_dst_file
);
1814 /* And do a ping that will make stuff easier to debug */
1815 qemu_savevm_send_ping(s
->to_dst_file
, 1);
1818 if (migrate_postcopy_ram()) {
1820 * Tell the destination that we *might* want to do postcopy later;
1821 * if the other end can't do postcopy it should fail now, nice and
1824 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
1827 qemu_savevm_state_begin(s
->to_dst_file
);
1829 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
1830 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1831 MIGRATION_STATUS_ACTIVE
);
1833 trace_migration_thread_setup_complete();
1835 while (s
->state
== MIGRATION_STATUS_ACTIVE
||
1836 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1837 int64_t current_time
;
1838 uint64_t pending_size
;
1840 if (!qemu_file_rate_limit(s
->to_dst_file
)) {
1841 uint64_t pend_post
, pend_nonpost
;
1843 qemu_savevm_state_pending(s
->to_dst_file
, threshold_size
,
1844 &pend_nonpost
, &pend_post
);
1845 pending_size
= pend_nonpost
+ pend_post
;
1846 trace_migrate_pending(pending_size
, threshold_size
,
1847 pend_post
, pend_nonpost
);
1848 if (pending_size
&& pending_size
>= threshold_size
) {
1849 /* Still a significant amount to transfer */
1851 if (migrate_postcopy_ram() &&
1852 s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
&&
1853 pend_nonpost
<= threshold_size
&&
1854 atomic_read(&s
->start_postcopy
)) {
1856 if (!postcopy_start(s
, &old_vm_running
)) {
1857 current_active_state
= MIGRATION_STATUS_POSTCOPY_ACTIVE
;
1858 entered_postcopy
= true;
1863 /* Just another iteration step */
1864 qemu_savevm_state_iterate(s
->to_dst_file
, entered_postcopy
);
1866 trace_migration_thread_low_pending(pending_size
);
1867 migration_completion(s
, current_active_state
,
1868 &old_vm_running
, &start_time
);
1873 if (qemu_file_get_error(s
->to_dst_file
)) {
1874 migrate_set_state(&s
->state
, current_active_state
,
1875 MIGRATION_STATUS_FAILED
);
1876 trace_migration_thread_file_err();
1879 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1880 if (current_time
>= initial_time
+ BUFFER_DELAY
) {
1881 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
) -
1883 uint64_t time_spent
= current_time
- initial_time
;
1884 double bandwidth
= (double)transferred_bytes
/ time_spent
;
1885 threshold_size
= bandwidth
* s
->parameters
.downtime_limit
;
1887 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1888 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
1890 trace_migrate_transferred(transferred_bytes
, time_spent
,
1891 bandwidth
, threshold_size
);
1892 /* if we haven't sent anything, we don't want to recalculate
1893 10000 is a small enough number for our purposes */
1894 if (ram_counters
.dirty_pages_rate
&& transferred_bytes
> 10000) {
1895 s
->expected_downtime
= ram_counters
.dirty_pages_rate
*
1896 qemu_target_page_size() / bandwidth
;
1899 qemu_file_reset_rate_limit(s
->to_dst_file
);
1900 initial_time
= current_time
;
1901 initial_bytes
= qemu_ftell(s
->to_dst_file
);
1903 if (qemu_file_rate_limit(s
->to_dst_file
)) {
1904 /* usleep expects microseconds */
1905 g_usleep((initial_time
+ BUFFER_DELAY
- current_time
)*1000);
1909 trace_migration_thread_after_loop();
1910 /* If we enabled cpu throttling for auto-converge, turn it off. */
1911 cpu_throttle_stop();
1912 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1914 qemu_mutex_lock_iothread();
1916 * The resource has been allocated by migration will be reused in COLO
1917 * process, so don't release them.
1920 qemu_savevm_state_cleanup();
1922 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1923 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
);
1924 s
->total_time
= end_time
- s
->total_time
;
1925 if (!entered_postcopy
) {
1926 s
->downtime
= end_time
- start_time
;
1928 if (s
->total_time
) {
1929 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1930 ((double) s
->total_time
)) / 1000;
1932 runstate_set(RUN_STATE_POSTMIGRATE
);
1934 if (s
->state
== MIGRATION_STATUS_ACTIVE
&& enable_colo
) {
1935 migrate_start_colo_process(s
);
1936 qemu_savevm_state_cleanup();
1938 * Fixme: we will run VM in COLO no matter its old running state.
1939 * After exited COLO, we will keep running.
1941 old_vm_running
= true;
1943 if (old_vm_running
&& !entered_postcopy
) {
1946 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
1947 runstate_set(RUN_STATE_POSTMIGRATE
);
1951 qemu_bh_schedule(s
->cleanup_bh
);
1952 qemu_mutex_unlock_iothread();
1954 rcu_unregister_thread();
1958 void migrate_fd_connect(MigrationState
*s
)
1960 s
->expected_downtime
= s
->parameters
.downtime_limit
;
1961 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
1963 qemu_file_set_blocking(s
->to_dst_file
, true);
1964 qemu_file_set_rate_limit(s
->to_dst_file
,
1965 s
->parameters
.max_bandwidth
/ XFER_LIMIT_RATIO
);
1967 /* Notify before starting migration thread */
1968 notifier_list_notify(&migration_state_notifiers
, s
);
1971 * Open the return path; currently for postcopy but other things might
1974 if (migrate_postcopy_ram()) {
1975 if (open_return_path_on_source(s
)) {
1976 error_report("Unable to open return-path for postcopy");
1977 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1978 MIGRATION_STATUS_FAILED
);
1979 migrate_fd_cleanup(s
);
1984 migrate_compress_threads_create();
1985 qemu_thread_create(&s
->thread
, "live_migration", migration_thread
, s
,
1986 QEMU_THREAD_JOINABLE
);
1987 s
->migration_thread_running
= true;