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 "qemu/main-loop.h"
20 #include "migration/migration.h"
21 #include "migration/qemu-file.h"
22 #include "sysemu/sysemu.h"
23 #include "block/block.h"
24 #include "qapi/qmp/qerror.h"
25 #include "qapi/util.h"
26 #include "qemu/sockets.h"
28 #include "migration/block.h"
29 #include "migration/postcopy-ram.h"
30 #include "qemu/thread.h"
31 #include "qmp-commands.h"
33 #include "qapi-event.h"
35 #include "exec/memory.h"
36 #include "exec/address-spaces.h"
37 #include "io/channel-buffer.h"
39 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
41 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
43 #define BUFFER_DELAY 100
44 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
46 /* Default compression thread count */
47 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
48 /* Default decompression thread count, usually decompression is at
49 * least 4 times as fast as compression.*/
50 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
51 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
52 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
53 /* Define default autoconverge cpu throttle migration parameters */
54 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
55 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
57 /* Migration XBZRLE default cache size */
58 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
60 static NotifierList migration_state_notifiers
=
61 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
63 static bool deferred_incoming
;
66 * Current state of incoming postcopy; note this is not part of
67 * MigrationIncomingState since it's state is used during cleanup
68 * at the end as MIS is being freed.
70 static PostcopyState incoming_postcopy_state
;
72 /* When we add fault tolerance, we could have several
73 migrations at once. For now we don't need to add
74 dynamic creation of migration */
77 MigrationState
*migrate_get_current(void)
80 static MigrationState current_migration
= {
81 .state
= MIGRATION_STATUS_NONE
,
82 .bandwidth_limit
= MAX_THROTTLE
,
83 .xbzrle_cache_size
= DEFAULT_MIGRATE_CACHE_SIZE
,
86 .compress_level
= DEFAULT_MIGRATE_COMPRESS_LEVEL
,
87 .compress_threads
= DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT
,
88 .decompress_threads
= DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT
,
89 .cpu_throttle_initial
= DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL
,
90 .cpu_throttle_increment
= DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT
,
95 qemu_mutex_init(¤t_migration
.src_page_req_mutex
);
98 return ¤t_migration
;
102 static MigrationIncomingState
*mis_current
;
104 MigrationIncomingState
*migration_incoming_get_current(void)
109 MigrationIncomingState
*migration_incoming_state_new(QEMUFile
* f
)
111 mis_current
= g_new0(MigrationIncomingState
, 1);
112 mis_current
->from_src_file
= f
;
113 mis_current
->state
= MIGRATION_STATUS_NONE
;
114 QLIST_INIT(&mis_current
->loadvm_handlers
);
115 qemu_mutex_init(&mis_current
->rp_mutex
);
116 qemu_event_init(&mis_current
->main_thread_load_event
, false);
121 void migration_incoming_state_destroy(void)
123 qemu_event_destroy(&mis_current
->main_thread_load_event
);
124 loadvm_free_handlers(mis_current
);
133 uint8_t runstate
[100];
138 static GlobalState global_state
;
140 int global_state_store(void)
142 if (!runstate_store((char *)global_state
.runstate
,
143 sizeof(global_state
.runstate
))) {
144 error_report("runstate name too big: %s", global_state
.runstate
);
145 trace_migrate_state_too_big();
151 void global_state_store_running(void)
153 const char *state
= RunState_lookup
[RUN_STATE_RUNNING
];
154 strncpy((char *)global_state
.runstate
,
155 state
, sizeof(global_state
.runstate
));
158 static bool global_state_received(void)
160 return global_state
.received
;
163 static RunState
global_state_get_runstate(void)
165 return global_state
.state
;
168 void global_state_set_optional(void)
170 global_state
.optional
= true;
173 static bool global_state_needed(void *opaque
)
175 GlobalState
*s
= opaque
;
176 char *runstate
= (char *)s
->runstate
;
178 /* If it is not optional, it is mandatory */
180 if (s
->optional
== false) {
184 /* If state is running or paused, it is not needed */
186 if (strcmp(runstate
, "running") == 0 ||
187 strcmp(runstate
, "paused") == 0) {
191 /* for any other state it is needed */
195 static int global_state_post_load(void *opaque
, int version_id
)
197 GlobalState
*s
= opaque
;
198 Error
*local_err
= NULL
;
200 char *runstate
= (char *)s
->runstate
;
203 trace_migrate_global_state_post_load(runstate
);
205 r
= qapi_enum_parse(RunState_lookup
, runstate
, RUN_STATE__MAX
,
210 error_report_err(local_err
);
219 static void global_state_pre_save(void *opaque
)
221 GlobalState
*s
= opaque
;
223 trace_migrate_global_state_pre_save((char *)s
->runstate
);
224 s
->size
= strlen((char *)s
->runstate
) + 1;
227 static const VMStateDescription vmstate_globalstate
= {
228 .name
= "globalstate",
230 .minimum_version_id
= 1,
231 .post_load
= global_state_post_load
,
232 .pre_save
= global_state_pre_save
,
233 .needed
= global_state_needed
,
234 .fields
= (VMStateField
[]) {
235 VMSTATE_UINT32(size
, GlobalState
),
236 VMSTATE_BUFFER(runstate
, GlobalState
),
237 VMSTATE_END_OF_LIST()
241 void register_global_state(void)
243 /* We would use it independently that we receive it */
244 strcpy((char *)&global_state
.runstate
, "");
245 global_state
.received
= false;
246 vmstate_register(NULL
, 0, &vmstate_globalstate
, &global_state
);
249 static void migrate_generate_event(int new_state
)
251 if (migrate_use_events()) {
252 qapi_event_send_migration(new_state
, &error_abort
);
257 * Called on -incoming with a defer: uri.
258 * The migration can be started later after any parameters have been
261 static void deferred_incoming_migration(Error
**errp
)
263 if (deferred_incoming
) {
264 error_setg(errp
, "Incoming migration already deferred");
266 deferred_incoming
= true;
269 /* Request a range of pages from the source VM at the given
271 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
272 * as the last request (a name must have been given previously)
273 * Start: Address offset within the RB
274 * Len: Length in bytes required - must be a multiple of pagesize
276 void migrate_send_rp_req_pages(MigrationIncomingState
*mis
, const char *rbname
,
277 ram_addr_t start
, size_t len
)
279 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
280 size_t msglen
= 12; /* start + len */
282 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
283 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
286 int rbname_len
= strlen(rbname
);
287 assert(rbname_len
< 256);
289 bufc
[msglen
++] = rbname_len
;
290 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
291 msglen
+= rbname_len
;
292 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES_ID
, msglen
, bufc
);
294 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES
, msglen
, bufc
);
298 void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
302 qapi_event_send_migration(MIGRATION_STATUS_SETUP
, &error_abort
);
303 if (!strcmp(uri
, "defer")) {
304 deferred_incoming_migration(errp
);
305 } else if (strstart(uri
, "tcp:", &p
)) {
306 tcp_start_incoming_migration(p
, errp
);
308 } else if (strstart(uri
, "rdma:", &p
)) {
309 rdma_start_incoming_migration(p
, errp
);
311 } else if (strstart(uri
, "exec:", &p
)) {
312 exec_start_incoming_migration(p
, errp
);
313 } else if (strstart(uri
, "unix:", &p
)) {
314 unix_start_incoming_migration(p
, errp
);
315 } else if (strstart(uri
, "fd:", &p
)) {
316 fd_start_incoming_migration(p
, errp
);
318 error_setg(errp
, "unknown migration protocol: %s", uri
);
322 static void process_incoming_migration_bh(void *opaque
)
324 Error
*local_err
= NULL
;
325 MigrationIncomingState
*mis
= opaque
;
327 /* Make sure all file formats flush their mutable metadata */
328 bdrv_invalidate_cache_all(&local_err
);
330 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
331 MIGRATION_STATUS_FAILED
);
332 error_report_err(local_err
);
333 migrate_decompress_threads_join();
338 * This must happen after all error conditions are dealt with and
339 * we're sure the VM is going to be running on this host.
341 qemu_announce_self();
343 /* If global state section was not received or we are in running
344 state, we need to obey autostart. Any other state is set with
347 if (!global_state_received() ||
348 global_state_get_runstate() == RUN_STATE_RUNNING
) {
352 runstate_set(RUN_STATE_PAUSED
);
355 runstate_set(global_state_get_runstate());
357 migrate_decompress_threads_join();
359 * This must happen after any state changes since as soon as an external
360 * observer sees this event they might start to prod at the VM assuming
363 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
364 MIGRATION_STATUS_COMPLETED
);
365 qemu_bh_delete(mis
->bh
);
366 migration_incoming_state_destroy();
369 static void process_incoming_migration_co(void *opaque
)
371 QEMUFile
*f
= opaque
;
372 MigrationIncomingState
*mis
;
376 mis
= migration_incoming_state_new(f
);
377 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
378 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
379 MIGRATION_STATUS_ACTIVE
);
380 ret
= qemu_loadvm_state(f
);
382 ps
= postcopy_state_get();
383 trace_process_incoming_migration_co_end(ret
, ps
);
384 if (ps
!= POSTCOPY_INCOMING_NONE
) {
385 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
387 * Where a migration had postcopy enabled (and thus went to advise)
388 * but managed to complete within the precopy period, we can use
391 postcopy_ram_incoming_cleanup(mis
);
392 } else if (ret
>= 0) {
394 * Postcopy was started, cleanup should happen at the end of the
397 trace_process_incoming_migration_co_postcopy_end_main();
400 /* Else if something went wrong then just fall out of the normal exit */
404 free_xbzrle_decoded_buf();
407 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
408 MIGRATION_STATUS_FAILED
);
409 error_report("load of migration failed: %s", strerror(-ret
));
410 migrate_decompress_threads_join();
414 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
415 qemu_bh_schedule(mis
->bh
);
418 void process_incoming_migration(QEMUFile
*f
)
420 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
);
422 migrate_decompress_threads_create();
423 qemu_file_set_blocking(f
, false);
424 qemu_coroutine_enter(co
, f
);
428 void migration_set_incoming_channel(MigrationState
*s
,
431 QEMUFile
*f
= qemu_fopen_channel_input(ioc
);
433 process_incoming_migration(f
);
437 void migration_set_outgoing_channel(MigrationState
*s
,
440 QEMUFile
*f
= qemu_fopen_channel_output(ioc
);
444 migrate_fd_connect(s
);
449 * Send a message on the return channel back to the source
452 void migrate_send_rp_message(MigrationIncomingState
*mis
,
453 enum mig_rp_message_type message_type
,
454 uint16_t len
, void *data
)
456 trace_migrate_send_rp_message((int)message_type
, len
);
457 qemu_mutex_lock(&mis
->rp_mutex
);
458 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
459 qemu_put_be16(mis
->to_src_file
, len
);
460 qemu_put_buffer(mis
->to_src_file
, data
, len
);
461 qemu_fflush(mis
->to_src_file
);
462 qemu_mutex_unlock(&mis
->rp_mutex
);
466 * Send a 'SHUT' message on the return channel with the given value
467 * to indicate that we've finished with the RP. Non-0 value indicates
470 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
475 buf
= cpu_to_be32(value
);
476 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
480 * Send a 'PONG' message on the return channel with the given value
481 * (normally in response to a 'PING')
483 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
488 buf
= cpu_to_be32(value
);
489 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
492 /* amount of nanoseconds we are willing to wait for migration to be down.
493 * the choice of nanoseconds is because it is the maximum resolution that
494 * get_clock() can achieve. It is an internal measure. All user-visible
495 * units must be in seconds */
496 static uint64_t max_downtime
= 300000000;
498 uint64_t migrate_max_downtime(void)
503 MigrationCapabilityStatusList
*qmp_query_migrate_capabilities(Error
**errp
)
505 MigrationCapabilityStatusList
*head
= NULL
;
506 MigrationCapabilityStatusList
*caps
;
507 MigrationState
*s
= migrate_get_current();
510 caps
= NULL
; /* silence compiler warning */
511 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
513 head
= g_malloc0(sizeof(*caps
));
516 caps
->next
= g_malloc0(sizeof(*caps
));
520 g_malloc(sizeof(*caps
->value
));
521 caps
->value
->capability
= i
;
522 caps
->value
->state
= s
->enabled_capabilities
[i
];
528 MigrationParameters
*qmp_query_migrate_parameters(Error
**errp
)
530 MigrationParameters
*params
;
531 MigrationState
*s
= migrate_get_current();
533 params
= g_malloc0(sizeof(*params
));
534 params
->compress_level
= s
->parameters
.compress_level
;
535 params
->compress_threads
= s
->parameters
.compress_threads
;
536 params
->decompress_threads
= s
->parameters
.decompress_threads
;
537 params
->cpu_throttle_initial
= s
->parameters
.cpu_throttle_initial
;
538 params
->cpu_throttle_increment
= s
->parameters
.cpu_throttle_increment
;
544 * Return true if we're already in the middle of a migration
545 * (i.e. any of the active or setup states)
547 static bool migration_is_setup_or_active(int state
)
550 case MIGRATION_STATUS_ACTIVE
:
551 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
552 case MIGRATION_STATUS_SETUP
:
561 static void get_xbzrle_cache_stats(MigrationInfo
*info
)
563 if (migrate_use_xbzrle()) {
564 info
->has_xbzrle_cache
= true;
565 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
566 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
567 info
->xbzrle_cache
->bytes
= xbzrle_mig_bytes_transferred();
568 info
->xbzrle_cache
->pages
= xbzrle_mig_pages_transferred();
569 info
->xbzrle_cache
->cache_miss
= xbzrle_mig_pages_cache_miss();
570 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_mig_cache_miss_rate();
571 info
->xbzrle_cache
->overflow
= xbzrle_mig_pages_overflow();
575 MigrationInfo
*qmp_query_migrate(Error
**errp
)
577 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
578 MigrationState
*s
= migrate_get_current();
581 case MIGRATION_STATUS_NONE
:
582 /* no migration has happened ever */
584 case MIGRATION_STATUS_SETUP
:
585 info
->has_status
= true;
586 info
->has_total_time
= false;
588 case MIGRATION_STATUS_ACTIVE
:
589 case MIGRATION_STATUS_CANCELLING
:
590 info
->has_status
= true;
591 info
->has_total_time
= true;
592 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
594 info
->has_expected_downtime
= true;
595 info
->expected_downtime
= s
->expected_downtime
;
596 info
->has_setup_time
= true;
597 info
->setup_time
= s
->setup_time
;
599 info
->has_ram
= true;
600 info
->ram
= g_malloc0(sizeof(*info
->ram
));
601 info
->ram
->transferred
= ram_bytes_transferred();
602 info
->ram
->remaining
= ram_bytes_remaining();
603 info
->ram
->total
= ram_bytes_total();
604 info
->ram
->duplicate
= dup_mig_pages_transferred();
605 info
->ram
->skipped
= skipped_mig_pages_transferred();
606 info
->ram
->normal
= norm_mig_pages_transferred();
607 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
608 info
->ram
->dirty_pages_rate
= s
->dirty_pages_rate
;
609 info
->ram
->mbps
= s
->mbps
;
610 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
612 if (blk_mig_active()) {
613 info
->has_disk
= true;
614 info
->disk
= g_malloc0(sizeof(*info
->disk
));
615 info
->disk
->transferred
= blk_mig_bytes_transferred();
616 info
->disk
->remaining
= blk_mig_bytes_remaining();
617 info
->disk
->total
= blk_mig_bytes_total();
620 if (cpu_throttle_active()) {
621 info
->has_cpu_throttle_percentage
= true;
622 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
625 get_xbzrle_cache_stats(info
);
627 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
628 /* Mostly the same as active; TODO add some postcopy stats */
629 info
->has_status
= true;
630 info
->has_total_time
= true;
631 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
633 info
->has_expected_downtime
= true;
634 info
->expected_downtime
= s
->expected_downtime
;
635 info
->has_setup_time
= true;
636 info
->setup_time
= s
->setup_time
;
638 info
->has_ram
= true;
639 info
->ram
= g_malloc0(sizeof(*info
->ram
));
640 info
->ram
->transferred
= ram_bytes_transferred();
641 info
->ram
->remaining
= ram_bytes_remaining();
642 info
->ram
->total
= ram_bytes_total();
643 info
->ram
->duplicate
= dup_mig_pages_transferred();
644 info
->ram
->skipped
= skipped_mig_pages_transferred();
645 info
->ram
->normal
= norm_mig_pages_transferred();
646 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
647 info
->ram
->dirty_pages_rate
= s
->dirty_pages_rate
;
648 info
->ram
->mbps
= s
->mbps
;
649 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
651 if (blk_mig_active()) {
652 info
->has_disk
= true;
653 info
->disk
= g_malloc0(sizeof(*info
->disk
));
654 info
->disk
->transferred
= blk_mig_bytes_transferred();
655 info
->disk
->remaining
= blk_mig_bytes_remaining();
656 info
->disk
->total
= blk_mig_bytes_total();
659 get_xbzrle_cache_stats(info
);
661 case MIGRATION_STATUS_COMPLETED
:
662 get_xbzrle_cache_stats(info
);
664 info
->has_status
= true;
665 info
->has_total_time
= true;
666 info
->total_time
= s
->total_time
;
667 info
->has_downtime
= true;
668 info
->downtime
= s
->downtime
;
669 info
->has_setup_time
= true;
670 info
->setup_time
= s
->setup_time
;
672 info
->has_ram
= true;
673 info
->ram
= g_malloc0(sizeof(*info
->ram
));
674 info
->ram
->transferred
= ram_bytes_transferred();
675 info
->ram
->remaining
= 0;
676 info
->ram
->total
= ram_bytes_total();
677 info
->ram
->duplicate
= dup_mig_pages_transferred();
678 info
->ram
->skipped
= skipped_mig_pages_transferred();
679 info
->ram
->normal
= norm_mig_pages_transferred();
680 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
681 info
->ram
->mbps
= s
->mbps
;
682 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
684 case MIGRATION_STATUS_FAILED
:
685 info
->has_status
= true;
687 info
->has_error_desc
= true;
688 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
691 case MIGRATION_STATUS_CANCELLED
:
692 info
->has_status
= true;
695 info
->status
= s
->state
;
700 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList
*params
,
703 MigrationState
*s
= migrate_get_current();
704 MigrationCapabilityStatusList
*cap
;
706 if (migration_is_setup_or_active(s
->state
)) {
707 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
711 for (cap
= params
; cap
; cap
= cap
->next
) {
712 s
->enabled_capabilities
[cap
->value
->capability
] = cap
->value
->state
;
715 if (migrate_postcopy_ram()) {
716 if (migrate_use_compression()) {
717 /* The decompression threads asynchronously write into RAM
718 * rather than use the atomic copies needed to avoid
719 * userfaulting. It should be possible to fix the decompression
720 * threads for compatibility in future.
722 error_report("Postcopy is not currently compatible with "
724 s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
] =
730 void qmp_migrate_set_parameters(bool has_compress_level
,
731 int64_t compress_level
,
732 bool has_compress_threads
,
733 int64_t compress_threads
,
734 bool has_decompress_threads
,
735 int64_t decompress_threads
,
736 bool has_cpu_throttle_initial
,
737 int64_t cpu_throttle_initial
,
738 bool has_cpu_throttle_increment
,
739 int64_t cpu_throttle_increment
,
742 MigrationState
*s
= migrate_get_current();
744 if (has_compress_level
&& (compress_level
< 0 || compress_level
> 9)) {
745 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "compress_level",
746 "is invalid, it should be in the range of 0 to 9");
749 if (has_compress_threads
&&
750 (compress_threads
< 1 || compress_threads
> 255)) {
751 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
753 "is invalid, it should be in the range of 1 to 255");
756 if (has_decompress_threads
&&
757 (decompress_threads
< 1 || decompress_threads
> 255)) {
758 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
759 "decompress_threads",
760 "is invalid, it should be in the range of 1 to 255");
763 if (has_cpu_throttle_initial
&&
764 (cpu_throttle_initial
< 1 || cpu_throttle_initial
> 99)) {
765 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
766 "cpu_throttle_initial",
767 "an integer in the range of 1 to 99");
769 if (has_cpu_throttle_increment
&&
770 (cpu_throttle_increment
< 1 || cpu_throttle_increment
> 99)) {
771 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
772 "cpu_throttle_increment",
773 "an integer in the range of 1 to 99");
776 if (has_compress_level
) {
777 s
->parameters
.compress_level
= compress_level
;
779 if (has_compress_threads
) {
780 s
->parameters
.compress_threads
= compress_threads
;
782 if (has_decompress_threads
) {
783 s
->parameters
.decompress_threads
= decompress_threads
;
785 if (has_cpu_throttle_initial
) {
786 s
->parameters
.cpu_throttle_initial
= cpu_throttle_initial
;
788 if (has_cpu_throttle_increment
) {
789 s
->parameters
.cpu_throttle_increment
= cpu_throttle_increment
;
794 void qmp_migrate_start_postcopy(Error
**errp
)
796 MigrationState
*s
= migrate_get_current();
798 if (!migrate_postcopy_ram()) {
799 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
800 " the start of migration");
804 if (s
->state
== MIGRATION_STATUS_NONE
) {
805 error_setg(errp
, "Postcopy must be started after migration has been"
810 * we don't error if migration has finished since that would be racy
811 * with issuing this command.
813 atomic_set(&s
->start_postcopy
, true);
816 /* shared migration helpers */
818 void migrate_set_state(int *state
, int old_state
, int new_state
)
820 if (atomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
821 trace_migrate_set_state(new_state
);
822 migrate_generate_event(new_state
);
826 static void migrate_fd_cleanup(void *opaque
)
828 MigrationState
*s
= opaque
;
830 qemu_bh_delete(s
->cleanup_bh
);
831 s
->cleanup_bh
= NULL
;
835 if (s
->to_dst_file
) {
836 trace_migrate_fd_cleanup();
837 qemu_mutex_unlock_iothread();
838 if (s
->migration_thread_running
) {
839 qemu_thread_join(&s
->thread
);
840 s
->migration_thread_running
= false;
842 qemu_mutex_lock_iothread();
844 migrate_compress_threads_join();
845 qemu_fclose(s
->to_dst_file
);
846 s
->to_dst_file
= NULL
;
849 assert((s
->state
!= MIGRATION_STATUS_ACTIVE
) &&
850 (s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
));
852 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
853 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
854 MIGRATION_STATUS_CANCELLED
);
857 notifier_list_notify(&migration_state_notifiers
, s
);
860 void migrate_fd_error(MigrationState
*s
, const Error
*error
)
862 trace_migrate_fd_error(error
? error_get_pretty(error
) : "");
863 assert(s
->to_dst_file
== NULL
);
864 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
865 MIGRATION_STATUS_FAILED
);
867 s
->error
= error_copy(error
);
869 notifier_list_notify(&migration_state_notifiers
, s
);
872 static void migrate_fd_cancel(MigrationState
*s
)
875 QEMUFile
*f
= migrate_get_current()->to_dst_file
;
876 trace_migrate_fd_cancel();
878 if (s
->rp_state
.from_dst_file
) {
879 /* shutdown the rp socket, so causing the rp thread to shutdown */
880 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
884 old_state
= s
->state
;
885 if (!migration_is_setup_or_active(old_state
)) {
888 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
889 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
892 * If we're unlucky the migration code might be stuck somewhere in a
893 * send/write while the network has failed and is waiting to timeout;
894 * if we've got shutdown(2) available then we can force it to quit.
895 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
896 * called in a bh, so there is no race against this cancel.
898 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
899 qemu_file_shutdown(f
);
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(MigrationState
*s
)
931 return (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
934 bool migration_in_postcopy_after_devices(MigrationState
*s
)
936 return migration_in_postcopy(s
) && s
->postcopy_after_devices
;
939 MigrationState
*migrate_init(const MigrationParams
*params
)
941 MigrationState
*s
= migrate_get_current();
944 * Reinitialise all migration state, except
945 * parameters/capabilities that the user set, and
951 s
->to_dst_file
= NULL
;
952 s
->state
= MIGRATION_STATUS_NONE
;
954 s
->rp_state
.from_dst_file
= NULL
;
955 s
->rp_state
.error
= false;
958 s
->expected_downtime
= 0;
959 s
->dirty_pages_rate
= 0;
960 s
->dirty_bytes_rate
= 0;
962 s
->dirty_sync_count
= 0;
963 s
->start_postcopy
= false;
964 s
->postcopy_after_devices
= false;
965 s
->migration_thread_running
= false;
966 s
->last_req_rb
= NULL
;
967 error_free(s
->error
);
970 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
972 QSIMPLEQ_INIT(&s
->src_page_requests
);
974 s
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
978 static GSList
*migration_blockers
;
980 void migrate_add_blocker(Error
*reason
)
982 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
985 void migrate_del_blocker(Error
*reason
)
987 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
990 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
992 Error
*local_err
= NULL
;
993 static bool once
= true;
995 if (!deferred_incoming
) {
996 error_setg(errp
, "For use with '-incoming defer'");
1000 error_setg(errp
, "The incoming migration has already been started");
1003 qemu_start_incoming_migration(uri
, &local_err
);
1006 error_propagate(errp
, local_err
);
1013 bool migration_is_blocked(Error
**errp
)
1015 if (qemu_savevm_state_blocked(errp
)) {
1019 if (migration_blockers
) {
1020 *errp
= error_copy(migration_blockers
->data
);
1027 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1028 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1031 Error
*local_err
= NULL
;
1032 MigrationState
*s
= migrate_get_current();
1033 MigrationParams params
;
1036 params
.blk
= has_blk
&& blk
;
1037 params
.shared
= has_inc
&& inc
;
1039 if (migration_is_setup_or_active(s
->state
) ||
1040 s
->state
== MIGRATION_STATUS_CANCELLING
) {
1041 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1044 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1045 error_setg(errp
, "Guest is waiting for an incoming migration");
1049 if (migration_is_blocked(errp
)) {
1053 s
= migrate_init(¶ms
);
1055 if (strstart(uri
, "tcp:", &p
)) {
1056 tcp_start_outgoing_migration(s
, p
, &local_err
);
1058 } else if (strstart(uri
, "rdma:", &p
)) {
1059 rdma_start_outgoing_migration(s
, p
, &local_err
);
1061 } else if (strstart(uri
, "exec:", &p
)) {
1062 exec_start_outgoing_migration(s
, p
, &local_err
);
1063 } else if (strstart(uri
, "unix:", &p
)) {
1064 unix_start_outgoing_migration(s
, p
, &local_err
);
1065 } else if (strstart(uri
, "fd:", &p
)) {
1066 fd_start_outgoing_migration(s
, p
, &local_err
);
1068 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1069 "a valid migration protocol");
1070 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1071 MIGRATION_STATUS_FAILED
);
1076 migrate_fd_error(s
, local_err
);
1077 error_propagate(errp
, local_err
);
1082 void qmp_migrate_cancel(Error
**errp
)
1084 migrate_fd_cancel(migrate_get_current());
1087 void qmp_migrate_set_cache_size(int64_t value
, Error
**errp
)
1089 MigrationState
*s
= migrate_get_current();
1092 /* Check for truncation */
1093 if (value
!= (size_t)value
) {
1094 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1095 "exceeding address space");
1099 /* Cache should not be larger than guest ram size */
1100 if (value
> ram_bytes_total()) {
1101 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1102 "exceeds guest ram size ");
1106 new_size
= xbzrle_cache_resize(value
);
1108 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1109 "is smaller than page size");
1113 s
->xbzrle_cache_size
= new_size
;
1116 int64_t qmp_query_migrate_cache_size(Error
**errp
)
1118 return migrate_xbzrle_cache_size();
1121 void qmp_migrate_set_speed(int64_t value
, Error
**errp
)
1128 if (value
> SIZE_MAX
) {
1132 s
= migrate_get_current();
1133 s
->bandwidth_limit
= value
;
1134 if (s
->to_dst_file
) {
1135 qemu_file_set_rate_limit(s
->to_dst_file
,
1136 s
->bandwidth_limit
/ XFER_LIMIT_RATIO
);
1140 void qmp_migrate_set_downtime(double value
, Error
**errp
)
1143 value
= MAX(0, MIN(UINT64_MAX
, value
));
1144 max_downtime
= (uint64_t)value
;
1147 bool migrate_postcopy_ram(void)
1151 s
= migrate_get_current();
1153 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
1156 bool migrate_auto_converge(void)
1160 s
= migrate_get_current();
1162 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_AUTO_CONVERGE
];
1165 bool migrate_zero_blocks(void)
1169 s
= migrate_get_current();
1171 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_ZERO_BLOCKS
];
1174 bool migrate_use_compression(void)
1178 s
= migrate_get_current();
1180 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_COMPRESS
];
1183 int migrate_compress_level(void)
1187 s
= migrate_get_current();
1189 return s
->parameters
.compress_level
;
1192 int migrate_compress_threads(void)
1196 s
= migrate_get_current();
1198 return s
->parameters
.compress_threads
;
1201 int migrate_decompress_threads(void)
1205 s
= migrate_get_current();
1207 return s
->parameters
.decompress_threads
;
1210 bool migrate_use_events(void)
1214 s
= migrate_get_current();
1216 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_EVENTS
];
1219 int migrate_use_xbzrle(void)
1223 s
= migrate_get_current();
1225 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_XBZRLE
];
1228 int64_t migrate_xbzrle_cache_size(void)
1232 s
= migrate_get_current();
1234 return s
->xbzrle_cache_size
;
1237 /* migration thread support */
1239 * Something bad happened to the RP stream, mark an error
1240 * The caller shall print or trace something to indicate why
1242 static void mark_source_rp_bad(MigrationState
*s
)
1244 s
->rp_state
.error
= true;
1247 static struct rp_cmd_args
{
1248 ssize_t len
; /* -1 = variable */
1251 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1252 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1253 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1254 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1255 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1256 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1260 * Process a request for pages received on the return path,
1261 * We're allowed to send more than requested (e.g. to round to our page size)
1262 * and we don't need to send pages that have already been sent.
1264 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1265 ram_addr_t start
, size_t len
)
1267 long our_host_ps
= getpagesize();
1269 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1272 * Since we currently insist on matching page sizes, just sanity check
1273 * we're being asked for whole host pages.
1275 if (start
& (our_host_ps
-1) ||
1276 (len
& (our_host_ps
-1))) {
1277 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1278 " len: %zd", __func__
, start
, len
);
1279 mark_source_rp_bad(ms
);
1283 if (ram_save_queue_pages(ms
, rbname
, start
, len
)) {
1284 mark_source_rp_bad(ms
);
1289 * Handles messages sent on the return path towards the source VM
1292 static void *source_return_path_thread(void *opaque
)
1294 MigrationState
*ms
= opaque
;
1295 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1296 uint16_t header_len
, header_type
;
1298 uint32_t tmp32
, sibling_error
;
1299 ram_addr_t start
= 0; /* =0 to silence warning */
1300 size_t len
= 0, expected_len
;
1303 trace_source_return_path_thread_entry();
1304 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1305 migration_is_setup_or_active(ms
->state
)) {
1306 trace_source_return_path_thread_loop_top();
1307 header_type
= qemu_get_be16(rp
);
1308 header_len
= qemu_get_be16(rp
);
1310 if (header_type
>= MIG_RP_MSG_MAX
||
1311 header_type
== MIG_RP_MSG_INVALID
) {
1312 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1313 header_type
, header_len
);
1314 mark_source_rp_bad(ms
);
1318 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1319 header_len
!= rp_cmd_args
[header_type
].len
) ||
1320 header_len
> sizeof(buf
)) {
1321 error_report("RP: Received '%s' message (0x%04x) with"
1322 "incorrect length %d expecting %zu",
1323 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1324 (size_t)rp_cmd_args
[header_type
].len
);
1325 mark_source_rp_bad(ms
);
1329 /* We know we've got a valid header by this point */
1330 res
= qemu_get_buffer(rp
, buf
, header_len
);
1331 if (res
!= header_len
) {
1332 error_report("RP: Failed reading data for message 0x%04x"
1333 " read %d expected %d",
1334 header_type
, res
, header_len
);
1335 mark_source_rp_bad(ms
);
1339 /* OK, we have the message and the data */
1340 switch (header_type
) {
1341 case MIG_RP_MSG_SHUT
:
1342 sibling_error
= be32_to_cpup((uint32_t *)buf
);
1343 trace_source_return_path_thread_shut(sibling_error
);
1344 if (sibling_error
) {
1345 error_report("RP: Sibling indicated error %d", sibling_error
);
1346 mark_source_rp_bad(ms
);
1349 * We'll let the main thread deal with closing the RP
1350 * we could do a shutdown(2) on it, but we're the only user
1351 * anyway, so there's nothing gained.
1355 case MIG_RP_MSG_PONG
:
1356 tmp32
= be32_to_cpup((uint32_t *)buf
);
1357 trace_source_return_path_thread_pong(tmp32
);
1360 case MIG_RP_MSG_REQ_PAGES
:
1361 start
= be64_to_cpup((uint64_t *)buf
);
1362 len
= be32_to_cpup((uint32_t *)(buf
+ 8));
1363 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1366 case MIG_RP_MSG_REQ_PAGES_ID
:
1367 expected_len
= 12 + 1; /* header + termination */
1369 if (header_len
>= expected_len
) {
1370 start
= be64_to_cpup((uint64_t *)buf
);
1371 len
= be32_to_cpup((uint32_t *)(buf
+ 8));
1372 /* Now we expect an idstr */
1373 tmp32
= buf
[12]; /* Length of the following idstr */
1374 buf
[13 + tmp32
] = '\0';
1375 expected_len
+= tmp32
;
1377 if (header_len
!= expected_len
) {
1378 error_report("RP: Req_Page_id with length %d expecting %zd",
1379 header_len
, expected_len
);
1380 mark_source_rp_bad(ms
);
1383 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1390 if (qemu_file_get_error(rp
)) {
1391 trace_source_return_path_thread_bad_end();
1392 mark_source_rp_bad(ms
);
1395 trace_source_return_path_thread_end();
1397 ms
->rp_state
.from_dst_file
= NULL
;
1402 static int open_return_path_on_source(MigrationState
*ms
)
1405 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
1406 if (!ms
->rp_state
.from_dst_file
) {
1410 trace_open_return_path_on_source();
1411 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
1412 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
1414 trace_open_return_path_on_source_continue();
1419 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1420 static int await_return_path_close_on_source(MigrationState
*ms
)
1423 * If this is a normal exit then the destination will send a SHUT and the
1424 * rp_thread will exit, however if there's an error we need to cause
1427 if (qemu_file_get_error(ms
->to_dst_file
) && ms
->rp_state
.from_dst_file
) {
1429 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1430 * waiting for the destination.
1432 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
1433 mark_source_rp_bad(ms
);
1435 trace_await_return_path_close_on_source_joining();
1436 qemu_thread_join(&ms
->rp_state
.rp_thread
);
1437 trace_await_return_path_close_on_source_close();
1438 return ms
->rp_state
.error
;
1442 * Switch from normal iteration to postcopy
1443 * Returns non-0 on error
1445 static int postcopy_start(MigrationState
*ms
, bool *old_vm_running
)
1448 QIOChannelBuffer
*bioc
;
1450 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1451 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
1452 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1454 trace_postcopy_start();
1455 qemu_mutex_lock_iothread();
1456 trace_postcopy_start_set_run();
1458 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1459 *old_vm_running
= runstate_is_running();
1460 global_state_store();
1461 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1466 ret
= bdrv_inactivate_all();
1472 * Cause any non-postcopiable, but iterative devices to
1473 * send out their final data.
1475 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true);
1478 * in Finish migrate and with the io-lock held everything should
1479 * be quiet, but we've potentially still got dirty pages and we
1480 * need to tell the destination to throw any pages it's already received
1483 if (ram_postcopy_send_discard_bitmap(ms
)) {
1484 error_report("postcopy send discard bitmap failed");
1489 * send rest of state - note things that are doing postcopy
1490 * will notice we're in POSTCOPY_ACTIVE and not actually
1491 * wrap their state up here
1493 qemu_file_set_rate_limit(ms
->to_dst_file
, INT64_MAX
);
1494 /* Ping just for debugging, helps line traces up */
1495 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
1498 * While loading the device state we may trigger page transfer
1499 * requests and the fd must be free to process those, and thus
1500 * the destination must read the whole device state off the fd before
1501 * it starts processing it. Unfortunately the ad-hoc migration format
1502 * doesn't allow the destination to know the size to read without fully
1503 * parsing it through each devices load-state code (especially the open
1504 * coded devices that use get/put).
1505 * So we wrap the device state up in a package with a length at the start;
1506 * to do this we use a qemu_buf to hold the whole of the device state.
1508 bioc
= qio_channel_buffer_new(4096);
1509 fb
= qemu_fopen_channel_output(QIO_CHANNEL(bioc
));
1510 object_unref(OBJECT(bioc
));
1513 * Make sure the receiver can get incoming pages before we send the rest
1516 qemu_savevm_send_postcopy_listen(fb
);
1518 qemu_savevm_state_complete_precopy(fb
, false);
1519 qemu_savevm_send_ping(fb
, 3);
1521 qemu_savevm_send_postcopy_run(fb
);
1523 /* <><> end of stuff going into the package */
1525 /* Now send that blob */
1526 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
1531 /* Send a notify to give a chance for anything that needs to happen
1532 * at the transition to postcopy and after the device state; in particular
1533 * spice needs to trigger a transition now
1535 ms
->postcopy_after_devices
= true;
1536 notifier_list_notify(&migration_state_notifiers
, ms
);
1538 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
1540 qemu_mutex_unlock_iothread();
1543 * Although this ping is just for debug, it could potentially be
1544 * used for getting a better measurement of downtime at the source.
1546 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
1548 ret
= qemu_file_get_error(ms
->to_dst_file
);
1550 error_report("postcopy_start: Migration stream errored");
1551 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1552 MIGRATION_STATUS_FAILED
);
1560 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1561 MIGRATION_STATUS_FAILED
);
1562 qemu_mutex_unlock_iothread();
1567 * migration_completion: Used by migration_thread when there's not much left.
1568 * The caller 'breaks' the loop when this returns.
1570 * @s: Current migration state
1571 * @current_active_state: The migration state we expect to be in
1572 * @*old_vm_running: Pointer to old_vm_running flag
1573 * @*start_time: Pointer to time to update
1575 static void migration_completion(MigrationState
*s
, int current_active_state
,
1576 bool *old_vm_running
,
1577 int64_t *start_time
)
1581 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1582 qemu_mutex_lock_iothread();
1583 *start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1584 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1585 *old_vm_running
= runstate_is_running();
1586 ret
= global_state_store();
1589 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1591 ret
= bdrv_inactivate_all();
1594 qemu_file_set_rate_limit(s
->to_dst_file
, INT64_MAX
);
1595 qemu_savevm_state_complete_precopy(s
->to_dst_file
, false);
1598 qemu_mutex_unlock_iothread();
1603 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1604 trace_migration_completion_postcopy_end();
1606 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
1607 trace_migration_completion_postcopy_end_after_complete();
1611 * If rp was opened we must clean up the thread before
1612 * cleaning everything else up (since if there are no failures
1613 * it will wait for the destination to send it's status in
1615 * Postcopy opens rp if enabled (even if it's not avtivated)
1617 if (migrate_postcopy_ram()) {
1619 trace_migration_completion_postcopy_end_before_rp();
1620 rp_error
= await_return_path_close_on_source(s
);
1621 trace_migration_completion_postcopy_end_after_rp(rp_error
);
1623 goto fail_invalidate
;
1627 if (qemu_file_get_error(s
->to_dst_file
)) {
1628 trace_migration_completion_file_err();
1629 goto fail_invalidate
;
1632 migrate_set_state(&s
->state
, current_active_state
,
1633 MIGRATION_STATUS_COMPLETED
);
1637 /* If not doing postcopy, vm_start() will be called: let's regain
1638 * control on images.
1640 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1641 Error
*local_err
= NULL
;
1643 bdrv_invalidate_cache_all(&local_err
);
1645 error_report_err(local_err
);
1650 migrate_set_state(&s
->state
, current_active_state
,
1651 MIGRATION_STATUS_FAILED
);
1655 * Master migration thread on the source VM.
1656 * It drives the migration and pumps the data down the outgoing channel.
1658 static void *migration_thread(void *opaque
)
1660 MigrationState
*s
= opaque
;
1661 /* Used by the bandwidth calcs, updated later */
1662 int64_t initial_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1663 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
1664 int64_t initial_bytes
= 0;
1665 int64_t max_size
= 0;
1666 int64_t start_time
= initial_time
;
1668 bool old_vm_running
= false;
1669 bool entered_postcopy
= false;
1670 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1671 enum MigrationStatus current_active_state
= MIGRATION_STATUS_ACTIVE
;
1673 rcu_register_thread();
1675 qemu_savevm_state_header(s
->to_dst_file
);
1677 if (migrate_postcopy_ram()) {
1678 /* Now tell the dest that it should open its end so it can reply */
1679 qemu_savevm_send_open_return_path(s
->to_dst_file
);
1681 /* And do a ping that will make stuff easier to debug */
1682 qemu_savevm_send_ping(s
->to_dst_file
, 1);
1685 * Tell the destination that we *might* want to do postcopy later;
1686 * if the other end can't do postcopy it should fail now, nice and
1689 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
1692 qemu_savevm_state_begin(s
->to_dst_file
, &s
->params
);
1694 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
1695 current_active_state
= MIGRATION_STATUS_ACTIVE
;
1696 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1697 MIGRATION_STATUS_ACTIVE
);
1699 trace_migration_thread_setup_complete();
1701 while (s
->state
== MIGRATION_STATUS_ACTIVE
||
1702 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1703 int64_t current_time
;
1704 uint64_t pending_size
;
1706 if (!qemu_file_rate_limit(s
->to_dst_file
)) {
1707 uint64_t pend_post
, pend_nonpost
;
1709 qemu_savevm_state_pending(s
->to_dst_file
, max_size
, &pend_nonpost
,
1711 pending_size
= pend_nonpost
+ pend_post
;
1712 trace_migrate_pending(pending_size
, max_size
,
1713 pend_post
, pend_nonpost
);
1714 if (pending_size
&& pending_size
>= max_size
) {
1715 /* Still a significant amount to transfer */
1717 if (migrate_postcopy_ram() &&
1718 s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
&&
1719 pend_nonpost
<= max_size
&&
1720 atomic_read(&s
->start_postcopy
)) {
1722 if (!postcopy_start(s
, &old_vm_running
)) {
1723 current_active_state
= MIGRATION_STATUS_POSTCOPY_ACTIVE
;
1724 entered_postcopy
= true;
1729 /* Just another iteration step */
1730 qemu_savevm_state_iterate(s
->to_dst_file
, entered_postcopy
);
1732 trace_migration_thread_low_pending(pending_size
);
1733 migration_completion(s
, current_active_state
,
1734 &old_vm_running
, &start_time
);
1739 if (qemu_file_get_error(s
->to_dst_file
)) {
1740 migrate_set_state(&s
->state
, current_active_state
,
1741 MIGRATION_STATUS_FAILED
);
1742 trace_migration_thread_file_err();
1745 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1746 if (current_time
>= initial_time
+ BUFFER_DELAY
) {
1747 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
) -
1749 uint64_t time_spent
= current_time
- initial_time
;
1750 double bandwidth
= (double)transferred_bytes
/ time_spent
;
1751 max_size
= bandwidth
* migrate_max_downtime() / 1000000;
1753 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1754 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
1756 trace_migrate_transferred(transferred_bytes
, time_spent
,
1757 bandwidth
, max_size
);
1758 /* if we haven't sent anything, we don't want to recalculate
1759 10000 is a small enough number for our purposes */
1760 if (s
->dirty_bytes_rate
&& transferred_bytes
> 10000) {
1761 s
->expected_downtime
= s
->dirty_bytes_rate
/ bandwidth
;
1764 qemu_file_reset_rate_limit(s
->to_dst_file
);
1765 initial_time
= current_time
;
1766 initial_bytes
= qemu_ftell(s
->to_dst_file
);
1768 if (qemu_file_rate_limit(s
->to_dst_file
)) {
1769 /* usleep expects microseconds */
1770 g_usleep((initial_time
+ BUFFER_DELAY
- current_time
)*1000);
1774 trace_migration_thread_after_loop();
1775 /* If we enabled cpu throttling for auto-converge, turn it off. */
1776 cpu_throttle_stop();
1777 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1779 qemu_mutex_lock_iothread();
1780 qemu_savevm_state_cleanup();
1781 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1782 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
);
1783 s
->total_time
= end_time
- s
->total_time
;
1784 if (!entered_postcopy
) {
1785 s
->downtime
= end_time
- start_time
;
1787 if (s
->total_time
) {
1788 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1789 ((double) s
->total_time
)) / 1000;
1791 runstate_set(RUN_STATE_POSTMIGRATE
);
1793 if (old_vm_running
&& !entered_postcopy
) {
1797 qemu_bh_schedule(s
->cleanup_bh
);
1798 qemu_mutex_unlock_iothread();
1800 rcu_unregister_thread();
1804 void migrate_fd_connect(MigrationState
*s
)
1806 /* This is a best 1st approximation. ns to ms */
1807 s
->expected_downtime
= max_downtime
/1000000;
1808 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
1810 qemu_file_set_blocking(s
->to_dst_file
, true);
1811 qemu_file_set_rate_limit(s
->to_dst_file
,
1812 s
->bandwidth_limit
/ XFER_LIMIT_RATIO
);
1814 /* Notify before starting migration thread */
1815 notifier_list_notify(&migration_state_notifiers
, s
);
1818 * Open the return path; currently for postcopy but other things might
1821 if (migrate_postcopy_ram()) {
1822 if (open_return_path_on_source(s
)) {
1823 error_report("Unable to open return-path for postcopy");
1824 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1825 MIGRATION_STATUS_FAILED
);
1826 migrate_fd_cleanup(s
);
1831 migrate_compress_threads_create();
1832 qemu_thread_create(&s
->thread
, "migration", migration_thread
, s
,
1833 QEMU_THREAD_JOINABLE
);
1834 s
->migration_thread_running
= true;
1837 PostcopyState
postcopy_state_get(void)
1839 return atomic_mb_read(&incoming_postcopy_state
);
1842 /* Set the state and return the old state */
1843 PostcopyState
postcopy_state_set(PostcopyState new_state
)
1845 return atomic_xchg(&incoming_postcopy_state
, new_state
);