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"
45 #include "hw/boards.h"
46 #include "monitor/monitor.h"
48 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
50 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
52 #define BUFFER_DELAY 100
53 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
55 /* Time in milliseconds we are allowed to stop the source,
56 * for sending the last part */
57 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
59 /* Maximum migrate downtime set to 2000 seconds */
60 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
61 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
63 /* Default compression thread count */
64 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
65 /* Default decompression thread count, usually decompression is at
66 * least 4 times as fast as compression.*/
67 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
68 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
69 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
70 /* Define default autoconverge cpu throttle migration parameters */
71 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
72 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
74 /* Migration XBZRLE default cache size */
75 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
77 /* The delay time (in ms) between two COLO checkpoints
78 * Note: Please change this default value to 10000 when we support hybrid mode.
80 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
82 static NotifierList migration_state_notifiers
=
83 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
85 static bool deferred_incoming
;
87 /* Messages sent on the return path from destination to source */
88 enum mig_rp_message_type
{
89 MIG_RP_MSG_INVALID
= 0, /* Must be 0 */
90 MIG_RP_MSG_SHUT
, /* sibling will not send any more RP messages */
91 MIG_RP_MSG_PONG
, /* Response to a PING; data (seq: be32 ) */
93 MIG_RP_MSG_REQ_PAGES_ID
, /* data (start: be64, len: be32, id: string) */
94 MIG_RP_MSG_REQ_PAGES
, /* data (start: be64, len: be32) */
99 /* When we add fault tolerance, we could have several
100 migrations at once. For now we don't need to add
101 dynamic creation of migration */
103 static MigrationState
*current_migration
;
105 void migration_object_init(void)
107 MachineState
*ms
= MACHINE(qdev_get_machine());
109 /* This can only be called once. */
110 assert(!current_migration
);
111 current_migration
= MIGRATION_OBJ(object_new(TYPE_MIGRATION
));
114 * We cannot really do this in migration_instance_init() since at
115 * that time global properties are not yet applied, then this
116 * value will be definitely replaced by something else.
118 if (ms
->enforce_config_section
) {
119 current_migration
->send_configuration
= true;
124 MigrationState
*migrate_get_current(void)
126 /* This can only be called after the object created. */
127 assert(current_migration
);
128 return current_migration
;
131 void migration_only_migratable_set(void)
133 migrate_get_current()->only_migratable
= true;
136 MigrationIncomingState
*migration_incoming_get_current(void)
139 static MigrationIncomingState mis_current
;
142 mis_current
.state
= MIGRATION_STATUS_NONE
;
143 memset(&mis_current
, 0, sizeof(MigrationIncomingState
));
144 qemu_mutex_init(&mis_current
.rp_mutex
);
145 qemu_event_init(&mis_current
.main_thread_load_event
, false);
151 void migration_incoming_state_destroy(void)
153 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
155 if (mis
->to_src_file
) {
156 /* Tell source that we are done */
157 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
158 qemu_fclose(mis
->to_src_file
);
159 mis
->to_src_file
= NULL
;
162 if (mis
->from_src_file
) {
163 qemu_fclose(mis
->from_src_file
);
164 mis
->from_src_file
= NULL
;
167 qemu_event_destroy(&mis
->main_thread_load_event
);
170 static void migrate_generate_event(int new_state
)
172 if (migrate_use_events()) {
173 qapi_event_send_migration(new_state
, &error_abort
);
178 * Called on -incoming with a defer: uri.
179 * The migration can be started later after any parameters have been
182 static void deferred_incoming_migration(Error
**errp
)
184 if (deferred_incoming
) {
185 error_setg(errp
, "Incoming migration already deferred");
187 deferred_incoming
= true;
191 * Send a message on the return channel back to the source
194 static void migrate_send_rp_message(MigrationIncomingState
*mis
,
195 enum mig_rp_message_type message_type
,
196 uint16_t len
, void *data
)
198 trace_migrate_send_rp_message((int)message_type
, len
);
199 qemu_mutex_lock(&mis
->rp_mutex
);
200 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
201 qemu_put_be16(mis
->to_src_file
, len
);
202 qemu_put_buffer(mis
->to_src_file
, data
, len
);
203 qemu_fflush(mis
->to_src_file
);
204 qemu_mutex_unlock(&mis
->rp_mutex
);
207 /* Request a range of pages from the source VM at the given
209 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
210 * as the last request (a name must have been given previously)
211 * Start: Address offset within the RB
212 * Len: Length in bytes required - must be a multiple of pagesize
214 void migrate_send_rp_req_pages(MigrationIncomingState
*mis
, const char *rbname
,
215 ram_addr_t start
, size_t len
)
217 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
218 size_t msglen
= 12; /* start + len */
220 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
221 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
224 int rbname_len
= strlen(rbname
);
225 assert(rbname_len
< 256);
227 bufc
[msglen
++] = rbname_len
;
228 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
229 msglen
+= rbname_len
;
230 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES_ID
, msglen
, bufc
);
232 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES
, msglen
, bufc
);
236 void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
240 qapi_event_send_migration(MIGRATION_STATUS_SETUP
, &error_abort
);
241 if (!strcmp(uri
, "defer")) {
242 deferred_incoming_migration(errp
);
243 } else if (strstart(uri
, "tcp:", &p
)) {
244 tcp_start_incoming_migration(p
, errp
);
246 } else if (strstart(uri
, "rdma:", &p
)) {
247 rdma_start_incoming_migration(p
, errp
);
249 } else if (strstart(uri
, "exec:", &p
)) {
250 exec_start_incoming_migration(p
, errp
);
251 } else if (strstart(uri
, "unix:", &p
)) {
252 unix_start_incoming_migration(p
, errp
);
253 } else if (strstart(uri
, "fd:", &p
)) {
254 fd_start_incoming_migration(p
, errp
);
256 error_setg(errp
, "unknown migration protocol: %s", uri
);
260 static void process_incoming_migration_bh(void *opaque
)
262 Error
*local_err
= NULL
;
263 MigrationIncomingState
*mis
= opaque
;
265 /* Make sure all file formats flush their mutable metadata.
266 * If we get an error here, just don't restart the VM yet. */
267 bdrv_invalidate_cache_all(&local_err
);
269 error_report_err(local_err
);
275 * This must happen after all error conditions are dealt with and
276 * we're sure the VM is going to be running on this host.
278 qemu_announce_self();
280 /* If global state section was not received or we are in running
281 state, we need to obey autostart. Any other state is set with
284 if (!global_state_received() ||
285 global_state_get_runstate() == RUN_STATE_RUNNING
) {
289 runstate_set(RUN_STATE_PAUSED
);
292 runstate_set(global_state_get_runstate());
294 migrate_decompress_threads_join();
296 * This must happen after any state changes since as soon as an external
297 * observer sees this event they might start to prod at the VM assuming
300 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
301 MIGRATION_STATUS_COMPLETED
);
302 qemu_bh_delete(mis
->bh
);
303 migration_incoming_state_destroy();
306 static void process_incoming_migration_co(void *opaque
)
308 QEMUFile
*f
= opaque
;
309 MigrationIncomingState
*mis
= migration_incoming_get_current();
313 mis
->from_src_file
= f
;
314 mis
->largest_page_size
= qemu_ram_pagesize_largest();
315 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
316 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
317 MIGRATION_STATUS_ACTIVE
);
318 ret
= qemu_loadvm_state(f
);
320 ps
= postcopy_state_get();
321 trace_process_incoming_migration_co_end(ret
, ps
);
322 if (ps
!= POSTCOPY_INCOMING_NONE
) {
323 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
325 * Where a migration had postcopy enabled (and thus went to advise)
326 * but managed to complete within the precopy period, we can use
329 postcopy_ram_incoming_cleanup(mis
);
330 } else if (ret
>= 0) {
332 * Postcopy was started, cleanup should happen at the end of the
335 trace_process_incoming_migration_co_postcopy_end_main();
338 /* Else if something went wrong then just fall out of the normal exit */
341 /* we get COLO info, and know if we are in COLO mode */
342 if (!ret
&& migration_incoming_enable_colo()) {
343 mis
->migration_incoming_co
= qemu_coroutine_self();
344 qemu_thread_create(&mis
->colo_incoming_thread
, "COLO incoming",
345 colo_process_incoming_thread
, mis
, QEMU_THREAD_JOINABLE
);
346 mis
->have_colo_incoming_thread
= true;
347 qemu_coroutine_yield();
349 /* Wait checkpoint incoming thread exit before free resource */
350 qemu_thread_join(&mis
->colo_incoming_thread
);
354 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
355 MIGRATION_STATUS_FAILED
);
356 error_report("load of migration failed: %s", strerror(-ret
));
357 migrate_decompress_threads_join();
361 free_xbzrle_decoded_buf();
363 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
364 qemu_bh_schedule(mis
->bh
);
367 void migration_fd_process_incoming(QEMUFile
*f
)
369 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, f
);
371 migrate_decompress_threads_create();
372 qemu_file_set_blocking(f
, false);
373 qemu_coroutine_enter(co
);
377 * Send a 'SHUT' message on the return channel with the given value
378 * to indicate that we've finished with the RP. Non-0 value indicates
381 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
386 buf
= cpu_to_be32(value
);
387 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
391 * Send a 'PONG' message on the return channel with the given value
392 * (normally in response to a 'PING')
394 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
399 buf
= cpu_to_be32(value
);
400 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
403 MigrationCapabilityStatusList
*qmp_query_migrate_capabilities(Error
**errp
)
405 MigrationCapabilityStatusList
*head
= NULL
;
406 MigrationCapabilityStatusList
*caps
;
407 MigrationState
*s
= migrate_get_current();
410 caps
= NULL
; /* silence compiler warning */
411 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
412 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
413 if (i
== MIGRATION_CAPABILITY_BLOCK
) {
417 if (i
== MIGRATION_CAPABILITY_X_COLO
&& !colo_supported()) {
421 head
= g_malloc0(sizeof(*caps
));
424 caps
->next
= g_malloc0(sizeof(*caps
));
428 g_malloc(sizeof(*caps
->value
));
429 caps
->value
->capability
= i
;
430 caps
->value
->state
= s
->enabled_capabilities
[i
];
436 MigrationParameters
*qmp_query_migrate_parameters(Error
**errp
)
438 MigrationParameters
*params
;
439 MigrationState
*s
= migrate_get_current();
441 params
= g_malloc0(sizeof(*params
));
442 params
->has_compress_level
= true;
443 params
->compress_level
= s
->parameters
.compress_level
;
444 params
->has_compress_threads
= true;
445 params
->compress_threads
= s
->parameters
.compress_threads
;
446 params
->has_decompress_threads
= true;
447 params
->decompress_threads
= s
->parameters
.decompress_threads
;
448 params
->has_cpu_throttle_initial
= true;
449 params
->cpu_throttle_initial
= s
->parameters
.cpu_throttle_initial
;
450 params
->has_cpu_throttle_increment
= true;
451 params
->cpu_throttle_increment
= s
->parameters
.cpu_throttle_increment
;
452 params
->has_tls_creds
= !!s
->parameters
.tls_creds
;
453 params
->tls_creds
= g_strdup(s
->parameters
.tls_creds
);
454 params
->has_tls_hostname
= !!s
->parameters
.tls_hostname
;
455 params
->tls_hostname
= g_strdup(s
->parameters
.tls_hostname
);
456 params
->has_max_bandwidth
= true;
457 params
->max_bandwidth
= s
->parameters
.max_bandwidth
;
458 params
->has_downtime_limit
= true;
459 params
->downtime_limit
= s
->parameters
.downtime_limit
;
460 params
->has_x_checkpoint_delay
= true;
461 params
->x_checkpoint_delay
= s
->parameters
.x_checkpoint_delay
;
462 params
->has_block_incremental
= true;
463 params
->block_incremental
= s
->parameters
.block_incremental
;
469 * Return true if we're already in the middle of a migration
470 * (i.e. any of the active or setup states)
472 static bool migration_is_setup_or_active(int state
)
475 case MIGRATION_STATUS_ACTIVE
:
476 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
477 case MIGRATION_STATUS_SETUP
:
486 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
488 info
->has_ram
= true;
489 info
->ram
= g_malloc0(sizeof(*info
->ram
));
490 info
->ram
->transferred
= ram_counters
.transferred
;
491 info
->ram
->total
= ram_bytes_total();
492 info
->ram
->duplicate
= ram_counters
.duplicate
;
493 /* legacy value. It is not used anymore */
494 info
->ram
->skipped
= 0;
495 info
->ram
->normal
= ram_counters
.normal
;
496 info
->ram
->normal_bytes
= ram_counters
.normal
*
497 qemu_target_page_size();
498 info
->ram
->mbps
= s
->mbps
;
499 info
->ram
->dirty_sync_count
= ram_counters
.dirty_sync_count
;
500 info
->ram
->postcopy_requests
= ram_counters
.postcopy_requests
;
501 info
->ram
->page_size
= qemu_target_page_size();
503 if (migrate_use_xbzrle()) {
504 info
->has_xbzrle_cache
= true;
505 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
506 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
507 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
508 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
509 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
510 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
511 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
514 if (cpu_throttle_active()) {
515 info
->has_cpu_throttle_percentage
= true;
516 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
519 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
520 info
->ram
->remaining
= ram_bytes_remaining();
521 info
->ram
->dirty_pages_rate
= ram_counters
.dirty_pages_rate
;
525 static void populate_disk_info(MigrationInfo
*info
)
527 if (blk_mig_active()) {
528 info
->has_disk
= true;
529 info
->disk
= g_malloc0(sizeof(*info
->disk
));
530 info
->disk
->transferred
= blk_mig_bytes_transferred();
531 info
->disk
->remaining
= blk_mig_bytes_remaining();
532 info
->disk
->total
= blk_mig_bytes_total();
536 MigrationInfo
*qmp_query_migrate(Error
**errp
)
538 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
539 MigrationState
*s
= migrate_get_current();
542 case MIGRATION_STATUS_NONE
:
543 /* no migration has happened ever */
545 case MIGRATION_STATUS_SETUP
:
546 info
->has_status
= true;
547 info
->has_total_time
= false;
549 case MIGRATION_STATUS_ACTIVE
:
550 case MIGRATION_STATUS_CANCELLING
:
551 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
552 /* TODO add some postcopy stats */
553 info
->has_status
= true;
554 info
->has_total_time
= true;
555 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
557 info
->has_expected_downtime
= true;
558 info
->expected_downtime
= s
->expected_downtime
;
559 info
->has_setup_time
= true;
560 info
->setup_time
= s
->setup_time
;
562 populate_ram_info(info
, s
);
563 populate_disk_info(info
);
565 case MIGRATION_STATUS_COLO
:
566 info
->has_status
= true;
567 /* TODO: display COLO specific information (checkpoint info etc.) */
569 case MIGRATION_STATUS_COMPLETED
:
570 info
->has_status
= true;
571 info
->has_total_time
= true;
572 info
->total_time
= s
->total_time
;
573 info
->has_downtime
= true;
574 info
->downtime
= s
->downtime
;
575 info
->has_setup_time
= true;
576 info
->setup_time
= s
->setup_time
;
578 populate_ram_info(info
, s
);
580 case MIGRATION_STATUS_FAILED
:
581 info
->has_status
= true;
583 info
->has_error_desc
= true;
584 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
587 case MIGRATION_STATUS_CANCELLED
:
588 info
->has_status
= true;
591 info
->status
= s
->state
;
596 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList
*params
,
599 MigrationState
*s
= migrate_get_current();
600 MigrationCapabilityStatusList
*cap
;
601 bool old_postcopy_cap
= migrate_postcopy_ram();
603 if (migration_is_setup_or_active(s
->state
)) {
604 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
608 for (cap
= params
; cap
; cap
= cap
->next
) {
609 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
610 if (cap
->value
->capability
== MIGRATION_CAPABILITY_BLOCK
611 && cap
->value
->state
) {
612 error_setg(errp
, "QEMU compiled without old-style (blk/-b, inc/-i) "
614 error_append_hint(errp
, "Use drive_mirror+NBD instead.\n");
618 if (cap
->value
->capability
== MIGRATION_CAPABILITY_X_COLO
) {
619 if (!colo_supported()) {
620 error_setg(errp
, "COLO is not currently supported, please"
621 " configure with --enable-colo option in order to"
622 " support COLO feature");
626 s
->enabled_capabilities
[cap
->value
->capability
] = cap
->value
->state
;
629 if (migrate_postcopy_ram()) {
630 if (migrate_use_compression()) {
631 /* The decompression threads asynchronously write into RAM
632 * rather than use the atomic copies needed to avoid
633 * userfaulting. It should be possible to fix the decompression
634 * threads for compatibility in future.
636 error_report("Postcopy is not currently compatible with "
638 s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
] =
641 /* This check is reasonably expensive, so only when it's being
642 * set the first time, also it's only the destination that needs
645 if (!old_postcopy_cap
&& runstate_check(RUN_STATE_INMIGRATE
) &&
646 !postcopy_ram_supported_by_host()) {
647 /* postcopy_ram_supported_by_host will have emitted a more
650 error_report("Postcopy is not supported");
651 s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
] =
657 void qmp_migrate_set_parameters(MigrationParameters
*params
, Error
**errp
)
659 MigrationState
*s
= migrate_get_current();
661 if (params
->has_compress_level
&&
662 (params
->compress_level
< 0 || params
->compress_level
> 9)) {
663 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "compress_level",
664 "is invalid, it should be in the range of 0 to 9");
667 if (params
->has_compress_threads
&&
668 (params
->compress_threads
< 1 || params
->compress_threads
> 255)) {
669 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
671 "is invalid, it should be in the range of 1 to 255");
674 if (params
->has_decompress_threads
&&
675 (params
->decompress_threads
< 1 || params
->decompress_threads
> 255)) {
676 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
677 "decompress_threads",
678 "is invalid, it should be in the range of 1 to 255");
681 if (params
->has_cpu_throttle_initial
&&
682 (params
->cpu_throttle_initial
< 1 ||
683 params
->cpu_throttle_initial
> 99)) {
684 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
685 "cpu_throttle_initial",
686 "an integer in the range of 1 to 99");
689 if (params
->has_cpu_throttle_increment
&&
690 (params
->cpu_throttle_increment
< 1 ||
691 params
->cpu_throttle_increment
> 99)) {
692 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
693 "cpu_throttle_increment",
694 "an integer in the range of 1 to 99");
697 if (params
->has_max_bandwidth
&&
698 (params
->max_bandwidth
< 0 || params
->max_bandwidth
> SIZE_MAX
)) {
699 error_setg(errp
, "Parameter 'max_bandwidth' expects an integer in the"
700 " range of 0 to %zu bytes/second", SIZE_MAX
);
703 if (params
->has_downtime_limit
&&
704 (params
->downtime_limit
< 0 ||
705 params
->downtime_limit
> MAX_MIGRATE_DOWNTIME
)) {
706 error_setg(errp
, "Parameter 'downtime_limit' expects an integer in "
707 "the range of 0 to %d milliseconds",
708 MAX_MIGRATE_DOWNTIME
);
711 if (params
->has_x_checkpoint_delay
&& (params
->x_checkpoint_delay
< 0)) {
712 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
713 "x_checkpoint_delay",
714 "is invalid, it should be positive");
717 if (params
->has_compress_level
) {
718 s
->parameters
.compress_level
= params
->compress_level
;
720 if (params
->has_compress_threads
) {
721 s
->parameters
.compress_threads
= params
->compress_threads
;
723 if (params
->has_decompress_threads
) {
724 s
->parameters
.decompress_threads
= params
->decompress_threads
;
726 if (params
->has_cpu_throttle_initial
) {
727 s
->parameters
.cpu_throttle_initial
= params
->cpu_throttle_initial
;
729 if (params
->has_cpu_throttle_increment
) {
730 s
->parameters
.cpu_throttle_increment
= params
->cpu_throttle_increment
;
732 if (params
->has_tls_creds
) {
733 g_free(s
->parameters
.tls_creds
);
734 s
->parameters
.tls_creds
= g_strdup(params
->tls_creds
);
736 if (params
->has_tls_hostname
) {
737 g_free(s
->parameters
.tls_hostname
);
738 s
->parameters
.tls_hostname
= g_strdup(params
->tls_hostname
);
740 if (params
->has_max_bandwidth
) {
741 s
->parameters
.max_bandwidth
= params
->max_bandwidth
;
742 if (s
->to_dst_file
) {
743 qemu_file_set_rate_limit(s
->to_dst_file
,
744 s
->parameters
.max_bandwidth
/ XFER_LIMIT_RATIO
);
747 if (params
->has_downtime_limit
) {
748 s
->parameters
.downtime_limit
= params
->downtime_limit
;
751 if (params
->has_x_checkpoint_delay
) {
752 s
->parameters
.x_checkpoint_delay
= params
->x_checkpoint_delay
;
753 if (migration_in_colo_state()) {
754 colo_checkpoint_notify(s
);
757 if (params
->has_block_incremental
) {
758 s
->parameters
.block_incremental
= params
->block_incremental
;
763 void qmp_migrate_start_postcopy(Error
**errp
)
765 MigrationState
*s
= migrate_get_current();
767 if (!migrate_postcopy_ram()) {
768 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
769 " the start of migration");
773 if (s
->state
== MIGRATION_STATUS_NONE
) {
774 error_setg(errp
, "Postcopy must be started after migration has been"
779 * we don't error if migration has finished since that would be racy
780 * with issuing this command.
782 atomic_set(&s
->start_postcopy
, true);
785 /* shared migration helpers */
787 void migrate_set_state(int *state
, int old_state
, int new_state
)
789 if (atomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
790 trace_migrate_set_state(new_state
);
791 migrate_generate_event(new_state
);
795 void migrate_set_block_enabled(bool value
, Error
**errp
)
797 MigrationCapabilityStatusList
*cap
;
799 cap
= g_new0(MigrationCapabilityStatusList
, 1);
800 cap
->value
= g_new0(MigrationCapabilityStatus
, 1);
801 cap
->value
->capability
= MIGRATION_CAPABILITY_BLOCK
;
802 cap
->value
->state
= value
;
803 qmp_migrate_set_capabilities(cap
, errp
);
804 qapi_free_MigrationCapabilityStatusList(cap
);
807 static void migrate_set_block_incremental(MigrationState
*s
, bool value
)
809 s
->parameters
.block_incremental
= value
;
812 static void block_cleanup_parameters(MigrationState
*s
)
814 if (s
->must_remove_block_options
) {
815 /* setting to false can never fail */
816 migrate_set_block_enabled(false, &error_abort
);
817 migrate_set_block_incremental(s
, false);
818 s
->must_remove_block_options
= false;
822 static void migrate_fd_cleanup(void *opaque
)
824 MigrationState
*s
= opaque
;
826 qemu_bh_delete(s
->cleanup_bh
);
827 s
->cleanup_bh
= NULL
;
829 if (s
->to_dst_file
) {
830 trace_migrate_fd_cleanup();
831 qemu_mutex_unlock_iothread();
832 if (s
->migration_thread_running
) {
833 qemu_thread_join(&s
->thread
);
834 s
->migration_thread_running
= false;
836 qemu_mutex_lock_iothread();
838 migrate_compress_threads_join();
839 qemu_fclose(s
->to_dst_file
);
840 s
->to_dst_file
= NULL
;
843 assert((s
->state
!= MIGRATION_STATUS_ACTIVE
) &&
844 (s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
));
846 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
847 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
848 MIGRATION_STATUS_CANCELLED
);
851 notifier_list_notify(&migration_state_notifiers
, s
);
852 block_cleanup_parameters(s
);
855 void migrate_fd_error(MigrationState
*s
, const Error
*error
)
857 trace_migrate_fd_error(error_get_pretty(error
));
858 assert(s
->to_dst_file
== NULL
);
859 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
860 MIGRATION_STATUS_FAILED
);
862 s
->error
= error_copy(error
);
864 notifier_list_notify(&migration_state_notifiers
, s
);
865 block_cleanup_parameters(s
);
868 static void migrate_fd_cancel(MigrationState
*s
)
871 QEMUFile
*f
= migrate_get_current()->to_dst_file
;
872 trace_migrate_fd_cancel();
874 if (s
->rp_state
.from_dst_file
) {
875 /* shutdown the rp socket, so causing the rp thread to shutdown */
876 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
880 old_state
= s
->state
;
881 if (!migration_is_setup_or_active(old_state
)) {
884 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
885 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
888 * If we're unlucky the migration code might be stuck somewhere in a
889 * send/write while the network has failed and is waiting to timeout;
890 * if we've got shutdown(2) available then we can force it to quit.
891 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
892 * called in a bh, so there is no race against this cancel.
894 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
895 qemu_file_shutdown(f
);
897 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
898 Error
*local_err
= NULL
;
900 bdrv_invalidate_cache_all(&local_err
);
902 error_report_err(local_err
);
904 s
->block_inactive
= false;
907 block_cleanup_parameters(s
);
910 void add_migration_state_change_notifier(Notifier
*notify
)
912 notifier_list_add(&migration_state_notifiers
, notify
);
915 void remove_migration_state_change_notifier(Notifier
*notify
)
917 notifier_remove(notify
);
920 bool migration_in_setup(MigrationState
*s
)
922 return s
->state
== MIGRATION_STATUS_SETUP
;
925 bool migration_has_finished(MigrationState
*s
)
927 return s
->state
== MIGRATION_STATUS_COMPLETED
;
930 bool migration_has_failed(MigrationState
*s
)
932 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
933 s
->state
== MIGRATION_STATUS_FAILED
);
936 bool migration_in_postcopy(void)
938 MigrationState
*s
= migrate_get_current();
940 return (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
943 bool migration_in_postcopy_after_devices(MigrationState
*s
)
945 return migration_in_postcopy() && s
->postcopy_after_devices
;
948 bool migration_is_idle(void)
950 MigrationState
*s
= migrate_get_current();
953 case MIGRATION_STATUS_NONE
:
954 case MIGRATION_STATUS_CANCELLED
:
955 case MIGRATION_STATUS_COMPLETED
:
956 case MIGRATION_STATUS_FAILED
:
958 case MIGRATION_STATUS_SETUP
:
959 case MIGRATION_STATUS_CANCELLING
:
960 case MIGRATION_STATUS_ACTIVE
:
961 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
962 case MIGRATION_STATUS_COLO
:
964 case MIGRATION_STATUS__MAX
:
965 g_assert_not_reached();
971 MigrationState
*migrate_init(void)
973 MigrationState
*s
= migrate_get_current();
976 * Reinitialise all migration state, except
977 * parameters/capabilities that the user set, and
983 s
->to_dst_file
= NULL
;
984 s
->state
= MIGRATION_STATUS_NONE
;
985 s
->rp_state
.from_dst_file
= NULL
;
986 s
->rp_state
.error
= false;
989 s
->expected_downtime
= 0;
991 s
->start_postcopy
= false;
992 s
->postcopy_after_devices
= false;
993 s
->migration_thread_running
= false;
994 error_free(s
->error
);
997 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
999 s
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1003 static GSList
*migration_blockers
;
1005 int migrate_add_blocker(Error
*reason
, Error
**errp
)
1007 if (migrate_get_current()->only_migratable
) {
1008 error_propagate(errp
, error_copy(reason
));
1009 error_prepend(errp
, "disallowing migration blocker "
1010 "(--only_migratable) for: ");
1014 if (migration_is_idle()) {
1015 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
1019 error_propagate(errp
, error_copy(reason
));
1020 error_prepend(errp
, "disallowing migration blocker (migration in "
1025 void migrate_del_blocker(Error
*reason
)
1027 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
1030 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
1032 Error
*local_err
= NULL
;
1033 static bool once
= true;
1035 if (!deferred_incoming
) {
1036 error_setg(errp
, "For use with '-incoming defer'");
1040 error_setg(errp
, "The incoming migration has already been started");
1043 qemu_start_incoming_migration(uri
, &local_err
);
1046 error_propagate(errp
, local_err
);
1053 bool migration_is_blocked(Error
**errp
)
1055 if (qemu_savevm_state_blocked(errp
)) {
1059 if (migration_blockers
) {
1060 error_propagate(errp
, error_copy(migration_blockers
->data
));
1067 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1068 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1071 Error
*local_err
= NULL
;
1072 MigrationState
*s
= migrate_get_current();
1075 if (migration_is_setup_or_active(s
->state
) ||
1076 s
->state
== MIGRATION_STATUS_CANCELLING
||
1077 s
->state
== MIGRATION_STATUS_COLO
) {
1078 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1081 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1082 error_setg(errp
, "Guest is waiting for an incoming migration");
1086 if (migration_is_blocked(errp
)) {
1090 if ((has_blk
&& blk
) || (has_inc
&& inc
)) {
1091 if (migrate_use_block() || migrate_use_block_incremental()) {
1092 error_setg(errp
, "Command options are incompatible with "
1093 "current migration capabilities");
1096 migrate_set_block_enabled(true, &local_err
);
1098 error_propagate(errp
, local_err
);
1101 s
->must_remove_block_options
= true;
1104 if (has_inc
&& inc
) {
1105 migrate_set_block_incremental(s
, true);
1110 if (strstart(uri
, "tcp:", &p
)) {
1111 tcp_start_outgoing_migration(s
, p
, &local_err
);
1113 } else if (strstart(uri
, "rdma:", &p
)) {
1114 rdma_start_outgoing_migration(s
, p
, &local_err
);
1116 } else if (strstart(uri
, "exec:", &p
)) {
1117 exec_start_outgoing_migration(s
, p
, &local_err
);
1118 } else if (strstart(uri
, "unix:", &p
)) {
1119 unix_start_outgoing_migration(s
, p
, &local_err
);
1120 } else if (strstart(uri
, "fd:", &p
)) {
1121 fd_start_outgoing_migration(s
, p
, &local_err
);
1123 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1124 "a valid migration protocol");
1125 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1126 MIGRATION_STATUS_FAILED
);
1131 migrate_fd_error(s
, local_err
);
1132 error_propagate(errp
, local_err
);
1137 void qmp_migrate_cancel(Error
**errp
)
1139 migrate_fd_cancel(migrate_get_current());
1142 void qmp_migrate_set_cache_size(int64_t value
, Error
**errp
)
1144 MigrationState
*s
= migrate_get_current();
1147 /* Check for truncation */
1148 if (value
!= (size_t)value
) {
1149 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1150 "exceeding address space");
1154 /* Cache should not be larger than guest ram size */
1155 if (value
> ram_bytes_total()) {
1156 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1157 "exceeds guest ram size ");
1161 new_size
= xbzrle_cache_resize(value
);
1163 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1164 "is smaller than page size");
1168 s
->xbzrle_cache_size
= new_size
;
1171 int64_t qmp_query_migrate_cache_size(Error
**errp
)
1173 return migrate_xbzrle_cache_size();
1176 void qmp_migrate_set_speed(int64_t value
, Error
**errp
)
1178 MigrationParameters p
= {
1179 .has_max_bandwidth
= true,
1180 .max_bandwidth
= value
,
1183 qmp_migrate_set_parameters(&p
, errp
);
1186 void qmp_migrate_set_downtime(double value
, Error
**errp
)
1188 if (value
< 0 || value
> MAX_MIGRATE_DOWNTIME_SECONDS
) {
1189 error_setg(errp
, "Parameter 'downtime_limit' expects an integer in "
1190 "the range of 0 to %d seconds",
1191 MAX_MIGRATE_DOWNTIME_SECONDS
);
1195 value
*= 1000; /* Convert to milliseconds */
1196 value
= MAX(0, MIN(INT64_MAX
, value
));
1198 MigrationParameters p
= {
1199 .has_downtime_limit
= true,
1200 .downtime_limit
= value
,
1203 qmp_migrate_set_parameters(&p
, errp
);
1206 bool migrate_release_ram(void)
1210 s
= migrate_get_current();
1212 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_RELEASE_RAM
];
1215 bool migrate_postcopy_ram(void)
1219 s
= migrate_get_current();
1221 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
1224 bool migrate_auto_converge(void)
1228 s
= migrate_get_current();
1230 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_AUTO_CONVERGE
];
1233 bool migrate_zero_blocks(void)
1237 s
= migrate_get_current();
1239 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_ZERO_BLOCKS
];
1242 bool migrate_use_compression(void)
1246 s
= migrate_get_current();
1248 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_COMPRESS
];
1251 int migrate_compress_level(void)
1255 s
= migrate_get_current();
1257 return s
->parameters
.compress_level
;
1260 int migrate_compress_threads(void)
1264 s
= migrate_get_current();
1266 return s
->parameters
.compress_threads
;
1269 int migrate_decompress_threads(void)
1273 s
= migrate_get_current();
1275 return s
->parameters
.decompress_threads
;
1278 bool migrate_use_events(void)
1282 s
= migrate_get_current();
1284 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_EVENTS
];
1287 int migrate_use_xbzrle(void)
1291 s
= migrate_get_current();
1293 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_XBZRLE
];
1296 int64_t migrate_xbzrle_cache_size(void)
1300 s
= migrate_get_current();
1302 return s
->xbzrle_cache_size
;
1305 bool migrate_use_block(void)
1309 s
= migrate_get_current();
1311 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_BLOCK
];
1314 bool migrate_use_block_incremental(void)
1318 s
= migrate_get_current();
1320 return s
->parameters
.block_incremental
;
1323 /* migration thread support */
1325 * Something bad happened to the RP stream, mark an error
1326 * The caller shall print or trace something to indicate why
1328 static void mark_source_rp_bad(MigrationState
*s
)
1330 s
->rp_state
.error
= true;
1333 static struct rp_cmd_args
{
1334 ssize_t len
; /* -1 = variable */
1337 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1338 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1339 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1340 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1341 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1342 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1346 * Process a request for pages received on the return path,
1347 * We're allowed to send more than requested (e.g. to round to our page size)
1348 * and we don't need to send pages that have already been sent.
1350 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1351 ram_addr_t start
, size_t len
)
1353 long our_host_ps
= getpagesize();
1355 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1358 * Since we currently insist on matching page sizes, just sanity check
1359 * we're being asked for whole host pages.
1361 if (start
& (our_host_ps
-1) ||
1362 (len
& (our_host_ps
-1))) {
1363 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1364 " len: %zd", __func__
, start
, len
);
1365 mark_source_rp_bad(ms
);
1369 if (ram_save_queue_pages(rbname
, start
, len
)) {
1370 mark_source_rp_bad(ms
);
1375 * Handles messages sent on the return path towards the source VM
1378 static void *source_return_path_thread(void *opaque
)
1380 MigrationState
*ms
= opaque
;
1381 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1382 uint16_t header_len
, header_type
;
1384 uint32_t tmp32
, sibling_error
;
1385 ram_addr_t start
= 0; /* =0 to silence warning */
1386 size_t len
= 0, expected_len
;
1389 trace_source_return_path_thread_entry();
1390 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1391 migration_is_setup_or_active(ms
->state
)) {
1392 trace_source_return_path_thread_loop_top();
1393 header_type
= qemu_get_be16(rp
);
1394 header_len
= qemu_get_be16(rp
);
1396 if (header_type
>= MIG_RP_MSG_MAX
||
1397 header_type
== MIG_RP_MSG_INVALID
) {
1398 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1399 header_type
, header_len
);
1400 mark_source_rp_bad(ms
);
1404 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1405 header_len
!= rp_cmd_args
[header_type
].len
) ||
1406 header_len
> sizeof(buf
)) {
1407 error_report("RP: Received '%s' message (0x%04x) with"
1408 "incorrect length %d expecting %zu",
1409 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1410 (size_t)rp_cmd_args
[header_type
].len
);
1411 mark_source_rp_bad(ms
);
1415 /* We know we've got a valid header by this point */
1416 res
= qemu_get_buffer(rp
, buf
, header_len
);
1417 if (res
!= header_len
) {
1418 error_report("RP: Failed reading data for message 0x%04x"
1419 " read %d expected %d",
1420 header_type
, res
, header_len
);
1421 mark_source_rp_bad(ms
);
1425 /* OK, we have the message and the data */
1426 switch (header_type
) {
1427 case MIG_RP_MSG_SHUT
:
1428 sibling_error
= ldl_be_p(buf
);
1429 trace_source_return_path_thread_shut(sibling_error
);
1430 if (sibling_error
) {
1431 error_report("RP: Sibling indicated error %d", sibling_error
);
1432 mark_source_rp_bad(ms
);
1435 * We'll let the main thread deal with closing the RP
1436 * we could do a shutdown(2) on it, but we're the only user
1437 * anyway, so there's nothing gained.
1441 case MIG_RP_MSG_PONG
:
1442 tmp32
= ldl_be_p(buf
);
1443 trace_source_return_path_thread_pong(tmp32
);
1446 case MIG_RP_MSG_REQ_PAGES
:
1447 start
= ldq_be_p(buf
);
1448 len
= ldl_be_p(buf
+ 8);
1449 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1452 case MIG_RP_MSG_REQ_PAGES_ID
:
1453 expected_len
= 12 + 1; /* header + termination */
1455 if (header_len
>= expected_len
) {
1456 start
= ldq_be_p(buf
);
1457 len
= ldl_be_p(buf
+ 8);
1458 /* Now we expect an idstr */
1459 tmp32
= buf
[12]; /* Length of the following idstr */
1460 buf
[13 + tmp32
] = '\0';
1461 expected_len
+= tmp32
;
1463 if (header_len
!= expected_len
) {
1464 error_report("RP: Req_Page_id with length %d expecting %zd",
1465 header_len
, expected_len
);
1466 mark_source_rp_bad(ms
);
1469 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1476 if (qemu_file_get_error(rp
)) {
1477 trace_source_return_path_thread_bad_end();
1478 mark_source_rp_bad(ms
);
1481 trace_source_return_path_thread_end();
1483 ms
->rp_state
.from_dst_file
= NULL
;
1488 static int open_return_path_on_source(MigrationState
*ms
)
1491 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
1492 if (!ms
->rp_state
.from_dst_file
) {
1496 trace_open_return_path_on_source();
1497 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
1498 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
1500 trace_open_return_path_on_source_continue();
1505 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1506 static int await_return_path_close_on_source(MigrationState
*ms
)
1509 * If this is a normal exit then the destination will send a SHUT and the
1510 * rp_thread will exit, however if there's an error we need to cause
1513 if (qemu_file_get_error(ms
->to_dst_file
) && ms
->rp_state
.from_dst_file
) {
1515 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1516 * waiting for the destination.
1518 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
1519 mark_source_rp_bad(ms
);
1521 trace_await_return_path_close_on_source_joining();
1522 qemu_thread_join(&ms
->rp_state
.rp_thread
);
1523 trace_await_return_path_close_on_source_close();
1524 return ms
->rp_state
.error
;
1528 * Switch from normal iteration to postcopy
1529 * Returns non-0 on error
1531 static int postcopy_start(MigrationState
*ms
, bool *old_vm_running
)
1534 QIOChannelBuffer
*bioc
;
1536 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1537 bool restart_block
= false;
1538 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
1539 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1541 trace_postcopy_start();
1542 qemu_mutex_lock_iothread();
1543 trace_postcopy_start_set_run();
1545 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1546 *old_vm_running
= runstate_is_running();
1547 global_state_store();
1548 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1553 ret
= bdrv_inactivate_all();
1557 restart_block
= true;
1560 * Cause any non-postcopiable, but iterative devices to
1561 * send out their final data.
1563 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
1566 * in Finish migrate and with the io-lock held everything should
1567 * be quiet, but we've potentially still got dirty pages and we
1568 * need to tell the destination to throw any pages it's already received
1571 if (ram_postcopy_send_discard_bitmap(ms
)) {
1572 error_report("postcopy send discard bitmap failed");
1577 * send rest of state - note things that are doing postcopy
1578 * will notice we're in POSTCOPY_ACTIVE and not actually
1579 * wrap their state up here
1581 qemu_file_set_rate_limit(ms
->to_dst_file
, INT64_MAX
);
1582 /* Ping just for debugging, helps line traces up */
1583 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
1586 * While loading the device state we may trigger page transfer
1587 * requests and the fd must be free to process those, and thus
1588 * the destination must read the whole device state off the fd before
1589 * it starts processing it. Unfortunately the ad-hoc migration format
1590 * doesn't allow the destination to know the size to read without fully
1591 * parsing it through each devices load-state code (especially the open
1592 * coded devices that use get/put).
1593 * So we wrap the device state up in a package with a length at the start;
1594 * to do this we use a qemu_buf to hold the whole of the device state.
1596 bioc
= qio_channel_buffer_new(4096);
1597 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
1598 fb
= qemu_fopen_channel_output(QIO_CHANNEL(bioc
));
1599 object_unref(OBJECT(bioc
));
1602 * Make sure the receiver can get incoming pages before we send the rest
1605 qemu_savevm_send_postcopy_listen(fb
);
1607 qemu_savevm_state_complete_precopy(fb
, false, false);
1608 qemu_savevm_send_ping(fb
, 3);
1610 qemu_savevm_send_postcopy_run(fb
);
1612 /* <><> end of stuff going into the package */
1614 /* Last point of recovery; as soon as we send the package the destination
1615 * can open devices and potentially start running.
1616 * Lets just check again we've not got any errors.
1618 ret
= qemu_file_get_error(ms
->to_dst_file
);
1620 error_report("postcopy_start: Migration stream errored (pre package)");
1624 restart_block
= false;
1626 /* Now send that blob */
1627 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
1632 /* Send a notify to give a chance for anything that needs to happen
1633 * at the transition to postcopy and after the device state; in particular
1634 * spice needs to trigger a transition now
1636 ms
->postcopy_after_devices
= true;
1637 notifier_list_notify(&migration_state_notifiers
, ms
);
1639 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
1641 qemu_mutex_unlock_iothread();
1644 * Although this ping is just for debug, it could potentially be
1645 * used for getting a better measurement of downtime at the source.
1647 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
1649 if (migrate_release_ram()) {
1650 ram_postcopy_migrated_memory_release(ms
);
1653 ret
= qemu_file_get_error(ms
->to_dst_file
);
1655 error_report("postcopy_start: Migration stream errored");
1656 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1657 MIGRATION_STATUS_FAILED
);
1665 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1666 MIGRATION_STATUS_FAILED
);
1667 if (restart_block
) {
1668 /* A failure happened early enough that we know the destination hasn't
1669 * accessed block devices, so we're safe to recover.
1671 Error
*local_err
= NULL
;
1673 bdrv_invalidate_cache_all(&local_err
);
1675 error_report_err(local_err
);
1678 qemu_mutex_unlock_iothread();
1683 * migration_completion: Used by migration_thread when there's not much left.
1684 * The caller 'breaks' the loop when this returns.
1686 * @s: Current migration state
1687 * @current_active_state: The migration state we expect to be in
1688 * @*old_vm_running: Pointer to old_vm_running flag
1689 * @*start_time: Pointer to time to update
1691 static void migration_completion(MigrationState
*s
, int current_active_state
,
1692 bool *old_vm_running
,
1693 int64_t *start_time
)
1697 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1698 qemu_mutex_lock_iothread();
1699 *start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1700 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1701 *old_vm_running
= runstate_is_running();
1702 ret
= global_state_store();
1705 bool inactivate
= !migrate_colo_enabled();
1706 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1708 qemu_file_set_rate_limit(s
->to_dst_file
, INT64_MAX
);
1709 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
1712 if (inactivate
&& ret
>= 0) {
1713 s
->block_inactive
= true;
1716 qemu_mutex_unlock_iothread();
1721 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1722 trace_migration_completion_postcopy_end();
1724 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
1725 trace_migration_completion_postcopy_end_after_complete();
1729 * If rp was opened we must clean up the thread before
1730 * cleaning everything else up (since if there are no failures
1731 * it will wait for the destination to send it's status in
1734 if (s
->rp_state
.from_dst_file
) {
1736 trace_migration_return_path_end_before();
1737 rp_error
= await_return_path_close_on_source(s
);
1738 trace_migration_return_path_end_after(rp_error
);
1740 goto fail_invalidate
;
1744 if (qemu_file_get_error(s
->to_dst_file
)) {
1745 trace_migration_completion_file_err();
1746 goto fail_invalidate
;
1749 if (!migrate_colo_enabled()) {
1750 migrate_set_state(&s
->state
, current_active_state
,
1751 MIGRATION_STATUS_COMPLETED
);
1757 /* If not doing postcopy, vm_start() will be called: let's regain
1758 * control on images.
1760 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1761 Error
*local_err
= NULL
;
1763 qemu_mutex_lock_iothread();
1764 bdrv_invalidate_cache_all(&local_err
);
1766 error_report_err(local_err
);
1768 s
->block_inactive
= false;
1770 qemu_mutex_unlock_iothread();
1774 migrate_set_state(&s
->state
, current_active_state
,
1775 MIGRATION_STATUS_FAILED
);
1778 bool migrate_colo_enabled(void)
1780 MigrationState
*s
= migrate_get_current();
1781 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_X_COLO
];
1785 * Master migration thread on the source VM.
1786 * It drives the migration and pumps the data down the outgoing channel.
1788 static void *migration_thread(void *opaque
)
1790 MigrationState
*s
= opaque
;
1791 /* Used by the bandwidth calcs, updated later */
1792 int64_t initial_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1793 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
1794 int64_t initial_bytes
= 0;
1796 * The final stage happens when the remaining data is smaller than
1797 * this threshold; it's calculated from the requested downtime and
1798 * measured bandwidth
1800 int64_t threshold_size
= 0;
1801 int64_t start_time
= initial_time
;
1803 bool old_vm_running
= false;
1804 bool entered_postcopy
= false;
1805 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1806 enum MigrationStatus current_active_state
= MIGRATION_STATUS_ACTIVE
;
1807 bool enable_colo
= migrate_colo_enabled();
1809 rcu_register_thread();
1811 qemu_savevm_state_header(s
->to_dst_file
);
1814 * If we opened the return path, we need to make sure dst has it
1817 if (s
->rp_state
.from_dst_file
) {
1818 /* Now tell the dest that it should open its end so it can reply */
1819 qemu_savevm_send_open_return_path(s
->to_dst_file
);
1821 /* And do a ping that will make stuff easier to debug */
1822 qemu_savevm_send_ping(s
->to_dst_file
, 1);
1825 if (migrate_postcopy_ram()) {
1827 * Tell the destination that we *might* want to do postcopy later;
1828 * if the other end can't do postcopy it should fail now, nice and
1831 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
1834 qemu_savevm_state_begin(s
->to_dst_file
);
1836 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
1837 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1838 MIGRATION_STATUS_ACTIVE
);
1840 trace_migration_thread_setup_complete();
1842 while (s
->state
== MIGRATION_STATUS_ACTIVE
||
1843 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1844 int64_t current_time
;
1845 uint64_t pending_size
;
1847 if (!qemu_file_rate_limit(s
->to_dst_file
)) {
1848 uint64_t pend_post
, pend_nonpost
;
1850 qemu_savevm_state_pending(s
->to_dst_file
, threshold_size
,
1851 &pend_nonpost
, &pend_post
);
1852 pending_size
= pend_nonpost
+ pend_post
;
1853 trace_migrate_pending(pending_size
, threshold_size
,
1854 pend_post
, pend_nonpost
);
1855 if (pending_size
&& pending_size
>= threshold_size
) {
1856 /* Still a significant amount to transfer */
1858 if (migrate_postcopy_ram() &&
1859 s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
&&
1860 pend_nonpost
<= threshold_size
&&
1861 atomic_read(&s
->start_postcopy
)) {
1863 if (!postcopy_start(s
, &old_vm_running
)) {
1864 current_active_state
= MIGRATION_STATUS_POSTCOPY_ACTIVE
;
1865 entered_postcopy
= true;
1870 /* Just another iteration step */
1871 qemu_savevm_state_iterate(s
->to_dst_file
, entered_postcopy
);
1873 trace_migration_thread_low_pending(pending_size
);
1874 migration_completion(s
, current_active_state
,
1875 &old_vm_running
, &start_time
);
1880 if (qemu_file_get_error(s
->to_dst_file
)) {
1881 migrate_set_state(&s
->state
, current_active_state
,
1882 MIGRATION_STATUS_FAILED
);
1883 trace_migration_thread_file_err();
1886 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1887 if (current_time
>= initial_time
+ BUFFER_DELAY
) {
1888 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
) -
1890 uint64_t time_spent
= current_time
- initial_time
;
1891 double bandwidth
= (double)transferred_bytes
/ time_spent
;
1892 threshold_size
= bandwidth
* s
->parameters
.downtime_limit
;
1894 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1895 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
1897 trace_migrate_transferred(transferred_bytes
, time_spent
,
1898 bandwidth
, threshold_size
);
1899 /* if we haven't sent anything, we don't want to recalculate
1900 10000 is a small enough number for our purposes */
1901 if (ram_counters
.dirty_pages_rate
&& transferred_bytes
> 10000) {
1902 s
->expected_downtime
= ram_counters
.dirty_pages_rate
*
1903 qemu_target_page_size() / bandwidth
;
1906 qemu_file_reset_rate_limit(s
->to_dst_file
);
1907 initial_time
= current_time
;
1908 initial_bytes
= qemu_ftell(s
->to_dst_file
);
1910 if (qemu_file_rate_limit(s
->to_dst_file
)) {
1911 /* usleep expects microseconds */
1912 g_usleep((initial_time
+ BUFFER_DELAY
- current_time
)*1000);
1916 trace_migration_thread_after_loop();
1917 /* If we enabled cpu throttling for auto-converge, turn it off. */
1918 cpu_throttle_stop();
1919 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1921 qemu_mutex_lock_iothread();
1923 * The resource has been allocated by migration will be reused in COLO
1924 * process, so don't release them.
1927 qemu_savevm_state_cleanup();
1929 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1930 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
);
1931 s
->total_time
= end_time
- s
->total_time
;
1932 if (!entered_postcopy
) {
1933 s
->downtime
= end_time
- start_time
;
1935 if (s
->total_time
) {
1936 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1937 ((double) s
->total_time
)) / 1000;
1939 runstate_set(RUN_STATE_POSTMIGRATE
);
1941 if (s
->state
== MIGRATION_STATUS_ACTIVE
&& enable_colo
) {
1942 migrate_start_colo_process(s
);
1943 qemu_savevm_state_cleanup();
1945 * Fixme: we will run VM in COLO no matter its old running state.
1946 * After exited COLO, we will keep running.
1948 old_vm_running
= true;
1950 if (old_vm_running
&& !entered_postcopy
) {
1953 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
1954 runstate_set(RUN_STATE_POSTMIGRATE
);
1958 qemu_bh_schedule(s
->cleanup_bh
);
1959 qemu_mutex_unlock_iothread();
1961 rcu_unregister_thread();
1965 void migrate_fd_connect(MigrationState
*s
)
1967 s
->expected_downtime
= s
->parameters
.downtime_limit
;
1968 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
1970 qemu_file_set_blocking(s
->to_dst_file
, true);
1971 qemu_file_set_rate_limit(s
->to_dst_file
,
1972 s
->parameters
.max_bandwidth
/ XFER_LIMIT_RATIO
);
1974 /* Notify before starting migration thread */
1975 notifier_list_notify(&migration_state_notifiers
, s
);
1978 * Open the return path; currently for postcopy but other things might
1981 if (migrate_postcopy_ram()) {
1982 if (open_return_path_on_source(s
)) {
1983 error_report("Unable to open return-path for postcopy");
1984 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1985 MIGRATION_STATUS_FAILED
);
1986 migrate_fd_cleanup(s
);
1991 migrate_compress_threads_create();
1992 qemu_thread_create(&s
->thread
, "live_migration", migration_thread
, s
,
1993 QEMU_THREAD_JOINABLE
);
1994 s
->migration_thread_running
= true;
1997 void migration_global_dump(Monitor
*mon
)
1999 MigrationState
*ms
= migrate_get_current();
2001 monitor_printf(mon
, "globals: store-global-state=%d, only_migratable=%d, "
2002 "send-configuration=%d, send-section-footer=%d\n",
2003 ms
->store_global_state
, ms
->only_migratable
,
2004 ms
->send_configuration
, ms
->send_section_footer
);
2007 static Property migration_properties
[] = {
2008 DEFINE_PROP_BOOL("store-global-state", MigrationState
,
2009 store_global_state
, true),
2010 DEFINE_PROP_BOOL("only-migratable", MigrationState
, only_migratable
, false),
2011 DEFINE_PROP_BOOL("send-configuration", MigrationState
,
2012 send_configuration
, true),
2013 DEFINE_PROP_BOOL("send-section-footer", MigrationState
,
2014 send_section_footer
, true),
2015 DEFINE_PROP_END_OF_LIST(),
2018 static void migration_class_init(ObjectClass
*klass
, void *data
)
2020 DeviceClass
*dc
= DEVICE_CLASS(klass
);
2022 dc
->user_creatable
= false;
2023 dc
->props
= migration_properties
;
2026 static void migration_instance_init(Object
*obj
)
2028 MigrationState
*ms
= MIGRATION_OBJ(obj
);
2030 ms
->state
= MIGRATION_STATUS_NONE
;
2031 ms
->xbzrle_cache_size
= DEFAULT_MIGRATE_CACHE_SIZE
;
2033 ms
->parameters
= (MigrationParameters
) {
2034 .compress_level
= DEFAULT_MIGRATE_COMPRESS_LEVEL
,
2035 .compress_threads
= DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT
,
2036 .decompress_threads
= DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT
,
2037 .cpu_throttle_initial
= DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL
,
2038 .cpu_throttle_increment
= DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT
,
2039 .max_bandwidth
= MAX_THROTTLE
,
2040 .downtime_limit
= DEFAULT_MIGRATE_SET_DOWNTIME
,
2041 .x_checkpoint_delay
= DEFAULT_MIGRATE_X_CHECKPOINT_DELAY
,
2043 ms
->parameters
.tls_creds
= g_strdup("");
2044 ms
->parameters
.tls_hostname
= g_strdup("");
2047 static const TypeInfo migration_type
= {
2048 .name
= TYPE_MIGRATION
,
2050 * NOTE: "migration" itself is not really a device. We used
2051 * TYPE_DEVICE here only to leverage some existing QDev features
2052 * like "-global" properties, and HW_COMPAT_* fields (which are
2053 * finally applied as global properties as well). If one day the
2054 * global property feature can be migrated from QDev to QObject in
2055 * general, then we can switch to QObject as well.
2057 .parent
= TYPE_DEVICE
,
2058 .class_init
= migration_class_init
,
2059 .class_size
= sizeof(MigrationClass
),
2060 .instance_size
= sizeof(MigrationState
),
2061 .instance_init
= migration_instance_init
,
2064 static void register_migration_types(void)
2066 type_register_static(&migration_type
);
2069 type_init(register_migration_types
);